LeetCode 24 Exchange the nodes in the linked list in pairs, the road of LeetCode for HERODING

Given a linked list, exchange adjacent nodes in it in pairs, and return the exchanged linked list.

You can't just change the value inside the node, but need to actually exchange the node.

Example:

Given 1->2->3->4, you should return 2->1->4->3.

Problem-solving idea:
Recursive call can solve this problem perfectly. First, use a next to point to head next, then connect head to recursive swapPairs (NodeList
), and then point next to head, so that node exchange is realized. the last remaining node directly returns, as follows:
*

/**
 * 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) {}
 * };
 */
class Solution {
    
    
public:
    ListNode* swapPairs(ListNode* head) {
    
    
        if(head == nullptr || head->next == nullptr){
    
    
            return head;
        }
        ListNode * next = head -> next;
        head -> next = swapPairs(next -> next);
        next -> next = head;
        return next;
    }
};

Guess you like

Origin blog.csdn.net/HERODING23/article/details/109044257