LeetCode 206 - reverse linked list

There are two ways to invert a single chain table: iterative method and recursive method.

1. Iterative method

  • The iterative method traverses the linked list from front to back, defines three pointers pointing to the adjacent three nodes respectively, reverses the first two nodes, that is, let the second node point to the first node. Then move the pointer back in turn until the second node is empty, and then handle the head and tail of the list.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
               
        if (head == NULL || head->next == NULL)     // Empty chain or only one node, directly return the head pointer
        {
            return head;            
        }
        else                                        // At least two nodes
        {
            ListNode * p1 = head;                   // First node
            ListNode * p2 = p1->next;               // Second node
            ListNode * p3 = p2->next;               // The third node

            while (p2)                              // The second node is empty, to the end of the chain, end
            {
                p3 = p2->next;
                p2->next = p1;                      // The second node points to the first node and reverses
                p1 = p2;                            // First node back
                p2 = p3;                            // Second node move back
            }
            
            head->next = NULL;          // The first node, the last node after inversion, points to NULL
            head = p1;                  // The head node points to the first node after reversal
            return head;
        }
    }
};

2. Recursive method

  • Baseline condition: empty chain or only one node, directly return the header pointer
  • Recursion condition: recursion call, return the head pointer after the reverse of the child linked list

Solution {
public:
    ListNode* reverseList(ListNode* head) {
    
        if (head == NULL || head->next == NULL)     // Empty chain or only one node, directly return the head pointer
        {
            return head;            
        }

        else                                        // There are more than two nodes
        {
            ListNode *new_head = reverseList(head->next); // Invert a sublist with the second node as its head
            
            // Head - > next now points to the last node of the sub linked list
            
            // Put the previous head node at the end of the child chain
            head->next->next = head;
            head->next = NULL;
            
            return new_head;
        }
    }
};

For more highlights, please pay attention to "seniusen"!

Posted by ronz on Mon, 16 Dec 2019 06:38:17 -0800