LeetCode One Question a Day (39) 24. Swap nodes in the linked list in pairs

24. Pairwise exchange of nodes in the linked list


Insert picture description here
Insert picture description here


answer:

/**
 * 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:
    // 1. start->p1->p2->end
    // 2. p1和p2表示要交换的两个节点,我们需要借助start和end两个节点来辅助完成交换;
    ListNode* swapPairs(ListNode* head) {
    
    
        ListNode *start,*p1,*p2,*end;
        p1=head;
        start=head;
        // 每两个节点作为一对处理
        while(p1!=nullptr){
    
    
            if(p1->next==nullptr) break;
            // 情况1:head节点需要特殊处理,因为这种情况p1没有前驱节点
            if(start==head){
    
     
                p2=p1->next;
                end=p2->next;
                p1->next=end;
                p2->next=p1;
                head=p2;
            }
            // 情况2:需要交换的两个节点在链表的中间部分
            else{
    
    
                p2=p1->next;
                end=p2->next;
                p1->next=end;
                p2->next=p1;
                start->next=p2;
            }
            // 下一对节点
            start=p1;
            p1=p1->next;
        }
        return head;
    }
};

Insert picture description here


Recursion:

class Solution {
    
    
public:
    ListNode* swapPairs(ListNode* head) {
    
    
        if (head == nullptr || head->next == nullptr) {
    
    
            return head;
        }
        ListNode* newHead = head->next;
        head->next = swapPairs(newHead->next);
        newHead->next = head;
        return newHead;
    }
};

Insert picture description here


The film "Win the Championship" tells the story of the Chinese women's volleyball team from winning the world championship in 1981 to the life-and-death battle between China and Pakistan in the Rio Olympics in 2016. It explains the legendary experience of generations of women's volleyball players who have gone through ups and downs but have been persistent and persistent.


Guess you like

Origin blog.csdn.net/qq_45021180/article/details/109061889