1. 题目
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.
2. 思路
遍历每次交换两个。
注意:两个相邻pair之间的链要注意更新好,比如1->4.
其实更简单的是直接递归完成,这样只需要处理前两个节点。
3. 代码
耗时:3ms
/**
* 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 || head->next == NULL) return head;
ListNode* p1 = head;
ListNode* p2 = p1->next;
while (p2 != NULL) {
int tmp = p1->val;
p1->val = p2->val;
p2->val = tmp;
p1 = p2->next;
p2 = NULL;
if (p1 != NULL) {
p2 = p1->next;
}
}
return head;
}
ListNode* swapPairs2(ListNode* head) {
if (head == NULL || head->next == NULL) return head;
ListNode* f = head->next;
ListNode* p1 = head;
ListNode* p2 = p1->next;
ListNode* pre = NULL;
while (p2 != NULL) {
ListNode* n = p2->next;
p2->next = p1;
p1->next = n;
if (pre != NULL) {
pre->next = p2;
}
pre = p1;
p1 = n;
p2 = NULL;
if (p1 != NULL) {
p2 = p1->next;
}
}
if (p1 != NULL) {
pre->next = p1;
p1->next = NULL;
}
return f;
}
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。