leetcode.24. Swap nodes in the linked list in pairs (swap-nodes-in-pairs)

Swap nodes in the linked list in pairs (swap-nodes-in-pairs)

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list’s nodes. Only nodes itself may be changed.

Example 1:
Insert picture description here

Input: head = [1,2,3,4]
Output: [2,1,4,3]

Example 2:

Input: head = []
Output: []

Example 3:

Input: head = [1]
Output: [1]

Code and ideas

Iteration

From the official swap-nodes-in-pairs node (swap-nodes-in-pairs) in the pairwise exchange list.
Insert picture description here
A dummy node is defined here, node1 and node2 are obtained, tempand they are exchanged, and the pointer moves forward. Note that the termination condition is tempbehind not only a node or nodes, no more nodes need to exchange, thus ending the exchange. When iterating, it is very important to think clearly about the termination condition.

class Solution {
    
    
public:
    ListNode* swapPairs(ListNode* head) {
    
    
    	//定义一个哑节点
        ListNode* dummyHead = new ListNode(0);
        dummyHead->next = head;
        ListNode* temp = dummyHead;
        while (temp->next != nullptr && temp->next->next != nullptr) {
    
    
        	//准备待交换的节点
            ListNode* node1 = temp->next;
            ListNode* node2 = temp->next->next;
            //交换
            temp->next = node2;
            node1->next = node2->next;
            node2->next = node1;
            //移动指针
            temp = node1;
        }
        //返回
        return dummyHead->next;
    }
};

Recursion (a bit difficult)

    public ListNode swapPairs(ListNode head) {
    
    
        //边界条件判断
        if (head == null || head.next == null)
            return head;
        //从第3个链表往后进行交换
        ListNode third = swapPairs(head.next.next);
        //从第3个链表往后都交换完了,我们只需要交换前两个链表即可,
        //这里我们把链表分为3组,分别是第1个节点,第2个节点,后面
        //的所有节点,也就是1 → 2 → 3,我们要把它变为2 → 1 → 3
        ListNode second = head.next;
        head.next = third;			//你可能会觉得,这里不是指向1吗
        second.next = head;
        
        return second;
    }

Description head.next = third;You may be wondering, this is not the point to 1the node it, why is pointing 3, attention, here a little bit different with the iterative approach, we return a new header node, it is called second. So, we used secondto connect the following node, you can also adjust the code format, like this look.

        			  head.next = third;
        second.next = head;

In other words second -> head -> third.

From sdwwld

other

Definition of ListNode


  Definition for singly-linked list.
  struct ListNode {
      int val;
      ListNode *next;
      ListNode() : val(0), next(nullptr) {}
      ListNode(int x) : val(x), next(nullptr) {}
      ListNode(int x, ListNode *next) : val(x), next(next) {}
  };

Guess you like

Origin blog.csdn.net/e891377/article/details/109046240