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;
}
};