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;
}
};