Simple stitching of the pointer with C++(Paint is good for understanding)


  • 0
    G
    class Solution {
    public:
        ListNode* swapPairs(ListNode* head) {
            ListNode* dummy=new ListNode(0);
            dummy->next=head;//添加一个哨兵并连接
            ListNode* pre=dummy;
            while(head&&head->next)
            {
                pre->next=head->next;
                head->next=head->next->next;
                pre->next->next=head;
                pre=head;
                head=head->next;
            }
            return dummy->next;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.