LeetCode Algorithm Recursive Class—Pairwise Exchange of Nodes in the Linked List

Table of contents

24. Exchange the nodes in the linked list two by two

answer:

code:

Running results:​Edit


Given a linked list, exchange the adjacent nodes in it two by two, and return the head node of the exchanged linked list. You must complete this exercise without modifying the values ​​inside the nodes (i.e. only node swaps).

Example 1:

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

Example 2:

Input: head = []
 Output: []

Example 3:

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

hint:

  • The number of nodes in the linked list is  [0, 100] within the range
  • 0 <= Node.val <= 100

 

answer:

  1. First, the recursion termination condition is checked. If the incoming head node is empty or there is only one node, return the head node directly, because no exchange is possible.

  2. Then, save the next node of the head node of the linked list to be processed rest. This is because we are recursively processing the rest of the linked list.

  3. Create a new head node newHead, pointing it to the node next to the original head node. This completes the exchange of adjacent nodes.

  4. Point the next node of the new head node to the original head node to complete the node exchange.

  5. Call the function recursively swapPairsand assign the result to the node next to the current head node. In this way, the processing of the remaining linked list is realized, and the result is correctly pointed to the next node of the current head node.

  6. Return the new head node.

In a recursive manner, two adjacent nodes are processed each time, and then the remaining part is processed recursively, and the adjacent node exchange operation of the entire linked list is finally completed.

code:

class Solution {
    public ListNode swapPairs(ListNode head) {
        //递归终止条件
        if(head==null||head.next==null) return head;
        //待处理链表
        ListNode rest=head.next.next;
        //新头节点交换
        ListNode newHead=head.next;
        newHead.next=head;
        //递归处理剩下的链表并将结果指向head.next
        head.next=swapPairs(rest);
        return newHead;
    }
}

operation result:

Guess you like

Origin blog.csdn.net/qq_62799214/article/details/132206854