Lituo classic question <Linked List Reversal> Solve the error heap-use-after-free

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

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

input: head = []
output: []

hint:

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

Source: LeetCode
Link: https://leetcode-cn.com/problems/UHnkqh
The copyright belongs to LeetCode. For commercial reprints, please contact the official authorization, for non-commercial reprints, please indicate the source.

This problem can be done by using a current node and the previous node. When traversing, add a temporary node, which is the next node of the current node. Then the loop condition is that the current node is not empty, and the traversal After completion, the current node is empty, and the previous node is output;

Then when I was doing it, I encountered an error report. I thought I wrote a good code but reported an error saying: heap-use-after-free. Yes, and the last node I defined starts with the head, so a cycle may have occurred, and the next of the head node is not NULL. I wanted to post my error code, but I accidentally deleted it. . . Anyway, the main mistake is that the pre node is initialized to head, and the correct one should be initialized to NULL

attach code

class Solution {
public:
    ListNode* reverseList(ListNode* head) 
    {
        ListNode* pre=NULL;
        ListNode* pos=head;
            while(pos!=NULL)
            {
            ListNode* temp=pos->next;
            pos->next = pre;
            pre = pos;
            pos = temp;  
            }
        return pre;       //最后循环完毕时 pos指向空 pre为最后一个结点
        }
}; 

Guess you like

Origin blog.csdn.net/mc10141222/article/details/123782259