LeetCode-206. Reverse Linked List

Reverse linked list

Title description

Reverse a singly linked list

Example 1 Language: C language
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

Idea analysis

Give three pointers, one n1 points to NULL, one n2 points to head, and one *n3 is used to save the address of the next node, and then n2 points to n1

The diagram is as follows:
Insert picture description here

Code

struct ListNode* reverseList(struct ListNode* head)
{
    
    
    if(head == NULL || head->next == NULL)
    {
    
    
        return head;
    }
    struct ListNode* n1 = NULL;
    struct ListNode* n2 = NULL;
    struct ListNode* n3 = NULL;
    n2 = head;
    //n3用于保存下一个节点的地址,防止n2指向n1后找不到下一个节点
    n3 = head->next;
    while(n2)
    {
    
    
        //n2指向n1
        n2->next = n1;
        //n1向后移到n2位置
        n1 = n2;
        //n2向后移到n3位置
        n2 = n3;
        if(n3)
        {
    
    
            n3 = n3->next;
        } 
    }
    return n1;
}

Guess you like

Origin blog.csdn.net/weixin_50886514/article/details/113484511