Swap Nodes in Pairs[medium]
Description
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.
Analysis
题目是很容易理解的。就是将相邻的结点交换,并且题目中明确要求不能直接交换结点的值,同时,从题目中我们能够看出他是每两个结点进行一次交换。我采用的方法是每三个结点交换后两个,首先创建一个结点h,它的next指针指向list的head,如果h的下一个和下下个均不为空,我们即可利用h来交换后两个结点,之后更新h的值,是他等于上一次处理的最后一个结点。
Solution
/**
* 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) {
ListNode* h = new ListNode(1);
h->next = head;
ListNode* c = h;
ListNode* p = NULL;
ListNode* t = NULL;
while (c->next != NULL &&c->next->next != NULL) {
p = c->next;
t = c->next->next;
p->next = t->next;
c->next = t;
t->next = p;
c = p;
}
return h->next;
}
};