Two ways to reverse a linked list

 reverse linked list

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

Method 1: Change the pointing of the pointer in the linked list

First define three pointers n1 n2 n3 , pointing to the following positions:

 Then it is a cyclic process. Each time the next of n2 points to n1, n2 is assigned to n3, and n3 points to the next  of n3, n1, n2 , and n3 can be continuously moved backward, as shown in the figure below:

 Note that the loop termination condition  is terminated only when n2 is a null pointer. At the same time, when n3 is a null pointer, n3->next cannot be made to point to null

The above method is designed for the linked list is not an empty list. If it is an empty linked list, the program will go wrong. At this time, you can directly return a null pointer.

code:

struct ListNode* reverseList(struct ListNode* head)
{
    if(head==NULL) //如果链表为空,直接返回空指针
    {
        return NULL;
    }
    struct ListNode*n1=NULL,*n2=head,*n3=head->next;
    while(n2)
    {
        n2->next=n1;
        n1=n2;
        n2=n3;
        if(n3!=NULL)
        {
            n3=n3->next;
        }
    }
    return n1;
}

Method 2: Move the data of the linked list each time

This method also needs to use three pointer variables, and the specific steps are similar to the above, as shown in the figure below:

 code:

struct ListNode* reverseList(struct ListNode* head)
{
    struct ListNode* newHead=NULL;
    struct ListNode* cur=head;
    while(cur)
    {
        struct ListNode*next=cur->next;
        cur->next=newHead;
        newHead=cur;
        cur=next;
    }
    return newHead;
}

 

Guess you like

Origin blog.csdn.net/m0_73648729/article/details/130476623