Featured image of post LeetCode 75 - 206. Reverse Linked List

LeetCode 75 - 206. Reverse Linked List

Description

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example 1:

img

1
2
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Example 2:

img

1
2
Input: head = [1,2]
Output: [2,1]

Example 3:

1
2
Input: head = []
Output: []

Constraints:

  • The number of nodes in the list is the range [0, 5000].
  • -5000 <= Node.val <= 5000

Solutions

Assume the linked list is (1→2→3→∅), and we want to change it to (∅←1←2←3).

While traversing the linked list, change the next pointer of the current node to point to the previous node. Since a node does not have a reference to its previous node, we must store the previous node beforehand. We also need to store the next node before changing the reference. Finally, return the new head reference.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* slow = nullptr;
        ListNode* current = head;

        while (current) {
            ListNode* next = current->next;
            current->next = slow;
            slow = current;
            current = next;
        }
        return slow;
    }
};