"Leetcode" 206. Reverse Linked List

Title description

Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Language : C language
thinking analysis
The method I first thought of is to store the data of each node in the original linked list from the end to the first, create a new linked list, and then create the nodes in turn based on the stored data, and finally return to the new linked list. , It is really troublesome to do so, use the following method:

  • Create three pointers prev, cur, next, make cur=head, and empty the other two pointers
  • The core idea is to make 1->NULL,2->1,3->2,4->3,5->4...and so on. At this time, you need to use the three pointers created in the previous one and a while loop. In this way, you can directly reverse a singly linked list
  • Given a loop while(cur), the first step is to make the next pointer equal to cur->next (acting as a save for the next node); then the second step is to make cur point to prev (the first node of the unreversed linked list) The next pointer points to the last node of the inverted linked list), because prev is empty at the beginning, so the first node points to NULL; the third step is to move the three pointers one step backward in turn, the operation is The first node of an unreversed linked list, the linked list is reversed after the cycle is completed
  • The last return must be prev, because after the last loop, cur points to NULL, and prev points to the last node of the original linked list, that is, points to the first node in the reversed linked list, which is equivalent to the head pointer of the original linked list.

Code

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

typedef struct ListNode Node;
struct ListNode* reverseList(struct ListNode* head){
    Node* prev = NULL;
    Node* cur= head;
    Node* next = NULL;

    while(cur)
    {
        next=cur->next;
        cur->next=prev;
        prev=cur;
        cur=next;
    }
    
    return prev;
}

operation result
Insert picture description here

Guess you like

Origin blog.csdn.net/NanlinW/article/details/104784299