[Data Structure OJ Question] Reverse Linked List

Original title link: https://leetcode.cn/problems/reverse-linked-list/description/

Table of contents

1. Description of the topic

2. Thinking analysis

3. Code implementation


1. Description of the topic

2. Thinking analysis

Method 1 : Three pointer flip method

Use three structure pointers n1 , n2 , n3 to modify the node pointing in place.

It is to let n1 point to the null pointer NULL first , n2 points to the head node , and n3 points to the next node of the head node .

Use n2 to traverse. Then let n1 point to n2 , n2 points to n3 , and n3 points to the next node of n3 . This loop traverses until n2 points to the null pointer NULL and stops .

Finally return to n1 .

Why use three pointers here?

Because if only two pointers are used, then after we let n1 point to n2, the connection of the linked list will be broken, and the next node of the original linked list n2 will not be found.

At the same time, we need to pay attention to some critical conditions and special cases .

For example, if the linked list is empty , we just let it return empty at the end .

Generally, at least one node exists, so we have to make n3 point to the next node of n2 when n2 is not empty (ie if(n2) ) . ( n3=n2->next )

During traversal, n3 must point to the next node , then n3 cannot be a null pointer (ie if(n3) n3=n3->next )

Method 2 : Head Insertion

Plug in every node

3. Code implementation

method one:

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


struct ListNode* reverseList(struct ListNode* head){
    struct ListNode *n1,*n2,*n3;
    n1=NULL;
    n2=head;
    if(n2)
        n3=n2->next;
    while(n2)
    {
        n2->next=n1;
        n1=n2;
        n2=n3;
        if(n3)
            n3=n3->next;
    }
    return n1;
}

Method Two:

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


struct ListNode* reverseList(struct ListNode* head){
    struct ListNode *cur=head;
    struct ListNode *newhead=NULL;
    while(cur)
    {
        struct ListNode *next=cur->next;
        //头插
        cur->next=newhead;
        newhead=cur;
        cur=next;
    }
    return newhead;
}

Guess you like

Origin blog.csdn.net/m0_62531913/article/details/132297310