#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!
让思维见见世面
浙公网安备 33010602011771号