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.
这题略蛋疼 做一下分析。 由于题目要求是不能直接更该链表节点的值,那意思就是让我们去交换链表指针。这个就有一点trap了 因为如果只是交换开头的两个节点head 和head->next 那很简单 head->next = head->next->next, head->next = head就完了,但是当你往前走到第二组数据的时候就会有问题了。这里我们假设要交换的第一个节点为first,第二个为second ,first前面的节点为extra 那么应该这么交换:
代码如下
/**
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if (head == NULL) return NULL;
if (head->next == NULL) return head;
ListNode *first = head, *second = head->next, *extra = NULL, *ret = head->next;
while(first && second)
{
if (extra != NULL)
{
extra->next = second;
}
first->next = second->next;
second->next = first;
extra = first;
first = first->next;
if (first)
second = first->next;
else
break;
}
return ret;
}
};