问题描述:
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.
由问题描述可知,这是一个单链表节点位置置换的问题。首先想到创建另一个辅助链表,按顺序两个两个地读取给定的单链表上的节点,交换读取的节点追加到辅助链表的后面,最后从辅助链表的第二个节点作为返回值,于是有了解法1。接着考虑能否不创建新的节点,直接在原给定的单链表上对节点本身的指向指针进行操作,来两两交换链表中节点的顺序。容易想到,每次一次循环要涉及到的是四个节点,因为若存在四个节点,那么第二个节点的下一节点是指向第四个节点。当然,若是第四个节点为空,那么则应指向第三个节点。若无第三和第四节点,则其指向空,所以我们可以得到以下解法2.
解法1:
/**
* 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)
return NULL;
if(!head->next)
return head;
ListNode* helper = new ListNode(0);
ListNode* pre = head;
ListNode* cur = helper;
ListNode* temp = NULL;
while(pre && pre->next)
{
cur->next = pre->next;
temp = pre->next->next;
pre->next->next = pre;
pre->next = NULL;
cur = pre;
pre = temp;
}
if(pre)
cur->next = pre;
return helper->next;
}
};
解法2:
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(!head)
return NULL;
if(head->next)
{
ListNode* pre = head;
head = head->next;
ListNode* temp = NULL;
while(pre&&pre->next)
{
temp = pre->next->next;
pre->next->next = pre;
if(temp&&temp->next)
{
pre->next = temp->next;
}else
{
pre->next = temp;
}
pre = temp;
}
}
return head;
}
};