Skip to content

Files

Latest commit

Dec 12, 2018
a9f0c4f · Dec 12, 2018

History

History
This branch is 2352 commits behind lzl124631x/LeetCode:master.

206. Reverse Linked List

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
Dec 12, 2018
Dec 12, 2018

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

Companies:
Microsoft, Facebook, Apple, Mathworks, Bloomberg, Adobe, Amazon, Yandex, Goldman Sachs, Google, Baidu, Nvidia, Expedia, Yahoo, Cisco

Related Topics:
Linked List

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/reverse-linked-list/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode dummy(0);
        while (head) {
            ListNode *node = head;
            head = head->next;
            node->next = dummy.next;
            dummy.next = node;
        }
        return dummy.next;
    }
};