leetcode24:Swap Nodes in Pairs

题目:

Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2->3->4, you should return the list as 2->1->4->3. Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

分析:

使用三个指针,P1指向第一个要交换的节点,,P2指向要交换的第二个节点。pre指向第一个要交换节点的前面一个节点。交换过程如下图所示:

第一步:p2=p1->next; 第二步: p1->next=p2->next; 第三步:p2->next=p1; 第四步:

->next=p2; elsehead=p2;

这样就完成了一次交换。 下面准备第二次交换的初始条件。 1、 更新prev:prev=p1; 2、更新第一个要交换的节点: p1=p1->next; 完整代码如下所示:

class Solution {public:ListNode *swapPairs(ListNode *head) {if(NULL==head||NULL==head->next)return head;ListNode *prev=head;ListNode *p1=head;ListNode *p2;do{p2=p1->next;p1->next=p2->next;p2->next=p1;if(prev!=head)prev->next=p2;elsehead=p2;prev=p1;p1=p1->next;}while(p1!=NULL && p1->next!=NULL);return head;}};

参考资料: 1: 2:https://leetcode.com/problems/swap-nodes-in-pairs/

旁观者的姓名永远爬不到比赛的计分板上。

leetcode24:Swap Nodes in Pairs

相关文章:

你感兴趣的文章:

标签云: