Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Note:
Your algorithm should use only constant extra space.
You may not modify the values in the list’s nodes, only nodes itself may be changed.
分析:这是一道链表操作的题,将链表中两两节点进行交换位置
解法一:
用两个指针,一次遍历,边遍历边改变指针,遍历完成,指针改变完成,返回头节点。并且由于头节点会变动,设立一个dummy节点指向头节点。指针比较多,移动时容易混淆,最好画图分析操作过程。
思路:
1.首先先弄一个不动的首节点,后面节点移动才不会受影响
以[1,2,3,4]为例,一开始要交换的是[1.2],因此需要先储存[3,4]稍后处理
2.储存后将list要处理的部分跟不处理的部分切开,切开的同时让[2]的next指向[1]
3.将前一个节点prev的next指向[2],因为[2]的节点已经指向了[1],因此这边已经完成了[1,2]–>[2,1]的步骤
4.接下来把之前存储的[3,4]接到[1]的后面,就可以继续处理[3,4]
代码如下:
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *prev = dummy, *cur = head;
while(cur && cur->next) {
prev->next = cur->next;
cur->next = cur->next->next;
prev->next->next = cur;
prev = cur;
cur = cur->next;
}
return dummy->next;
}
};
解法二:
此题利用递归解决非常简洁
实际上利用了回溯的思想,递归遍历到链表末尾,然后先交换末尾两个,然后依次往前交换:
代码如下:
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (!head || !head->next) return head;
ListNode *t = head->next;
head->next = swapPairs(head->next->next);
t->next = head;
return t;
}
};