[leetcode] 24 Swap Nodes in Pairs(交换链表相邻结 -电脑资料

电脑资料 时间:2019-01-01 我要投稿
【www.unjs.com - 电脑资料】

    (一)迭代法

    在处理这种问题时,我们通常加上一个dummy头结点指向head,至于思路很清晰了就是隔一个去交换两个相邻结点,比如1->2->3->4->NULL,我们先通过指针交换1和2,再交换3和4,详细的指针操作可以看下面的图:

   

class Solution {public:    ListNode* swapPairs(ListNode* head) {       ListNode *dummy=new ListNode(0);	   dummy->next=head;	   ListNode *prev=dummy,*cur=head;	   while(cur&&cur->next)	   {   	       prev->next=cur->next;		   cur->next=cur->next->next; //先确定后继 		   prev->next->next=cur;		   		   prev=cur;		   cur=cur->next;	   	   }      	   return dummy->next;    }};
(二)递归版本

    递归一向是以精巧著称,我们只需处理好最基础的一部分,剩下的递归即可,

[leetcode] 24 Swap Nodes in Pairs(交换链表相邻结

电脑资料

[leetcode] 24 Swap Nodes in Pairs(交换链表相邻结》(https://www.unjs.com)。如果读者不是很理解的话,可以手动模拟一下。

class Solution {public:    ListNode *swapPairs(ListNode *head) {       if (head == NULL)            return NULL;       if (head -> next == NULL)            return head;       ListNode *tmp = head -> next;       head -> next = swapPairs(tmp -> next);       tmp -> next = head; // 指向下一部分        return tmp;    }};

最新文章