您的位置:首页 > 其它

交换链表中的相邻节点

2013-04-24 11:33 344 查看
LeetCode中的题:

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.

分析:先交换链表的前两个节点,接下来每两个相邻节点可以通过重复的操作实现。

代码如下:

//Definition for singly-linked list.

struct ListNode {

int val;

ListNode *next;

ListNode(int x) : val(x), next(NULL) {}

};

class Solution {

public:

ListNode *swapPairs(ListNode *head) {

if(head==NULL)return NULL;

if(head->next==NULL)return head;

ListNode *tmp1=head;

head=head->next;

ListNode *tmp2=head->next;

head->next=tmp1;

tmp1->next=tmp2;

//ListNode *headtmp=head;

while(tmp1->next!=NULL&&tmp1->next->next!=NULL)

{

tmp2=tmp1->next;

tmp1->next=tmp2->next;

ListNode *tmp3=tmp2->next->next;

tmp1->next->next=tmp2;

tmp2->next=tmp3;

tmp1=tmp2;

}

return head;

}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: