Egbert Lin's Blog

“Life is not a race, but a journey to be savoured each step of the way” by Brian Dyson

[LeetCode Road] Reverse Linked List - Solution/C++

206. Reverse Linked List

Question:

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

Example:

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

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

Input: head = []
Output: []

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

    Version 1

    Idea:
    A demonstration is shonw as below:

    There are four steps to do: 1) Declare a curr variable that it's a pointer of ListNode to point head ListNode. Shift one position every loop. 2) Change a head->next to prev ListNode. It means proceeding the redirection or revering. Notice: prev ListNode is a new ListNOde with no value (only NULL). 3) Update prev to head. 4) Update head to curr. Repeat (1) - (4) steps until head is NULL.

    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
    26
    /**
    * 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) {
    if(!head) return head;

    ListNode* curr = head;
    ListNode* prev = NULL;
    while(head){
    curr = head->next;
    head->next = prev;
    prev = head;
    head = curr;
    }
    return prev;
    }
    };