Swap Nodes in Pairs

Posted hujianglang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swap Nodes in Pairs相关的知识,希望对你有一定的参考价值。

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

Example:

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

Note:

  • Your algorithm should use only constant extra space.
  • You may not modify the values in the list‘s nodes, only nodes itself may be changed.
class Solution
    public:
        ListNode* swapPairs(ListNode* head)
            ListNode *dummy = new ListNode(-1);
            ListNode *pre = dummy;
            
            dummy->next = head;
            while(pre->next && pre->next->next)
                ListNode *t = pre->next->next;
                pre->next->next = t->next;
                t->next = pre->next;
                pre->next = t;
                pre = t->next;  
            
            return dummy->next;
        
;

//递归写法稍微有些复杂
class Solution
    public:
        ListNode* swapPairs(ListNode* head)
            if(!head || !head->next) return head;
            ListNode *t = head->next;
            head->next = swapPairs(head->next->next);
            t->next = head;
            return t;
        
;

 

以上是关于Swap Nodes in Pairs的主要内容,如果未能解决你的问题,请参考以下文章

24. Swap Nodes in Pairs

LC_24. Swap Nodes in Pairs

Swap Nodes in Pairs

Swap Nodes in Pairs

Swap Nodes in Pairs

24. Swap Nodes in Pairs