#LeetCode 206 (#剑指offer24)

This problem let us reverse linked list.

Problem description:

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

This is my code and tutorial:

/**
 * 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* pre = NULL;  //Define the previous pointer

        ListNode* successor = NULL;  //Define the successor pointer

        //Execute while loop condition:head is a valid node
        while (head)
        {
            /*we should keep the next pointer,without it,
            we can't find the head of the left node*/

            successor = head -> next;

            head -> next = pre;  //And we let current pointer point to the previous 

            pre = head;  //update the previous pointer

            head = successor;  //update the current pointer
        }

        //When head(NULL) = successor(NULL),while loop will stop

        return pre;
    }
};

Wish this tutorial can help you!

posted @ 2022-03-25 16:13  越菜越自信  阅读(23)  评论(0)    收藏  举报