https://leetcode.com/problems/swap-nodes-in-pairs/
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
链表中元素两个一组交换顺序。
迭代法很直观,做个头结点然后一路换下去。
反向思考这个问题就会发现递归方法也可以做(因为这是对链表的局部操作,所以部分的链表等价于整个的链表),同时其中交换首节点和第二个节点的方法感觉似曾相识,好像在之前哪道题目中用到过。
这题中递归方法反而更快,可能是因为每一组中进行的指针赋值操作更少(5->2)
迭代法:
/**
* 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) {
ListNode fake_head(0);
fake_head.next = head;
ListNode *cur = &fake_head;
while(cur->next != NULL && cur->next->next != NULL){
ListNode *tem = cur->next;
cur->next = tem->next;
tem->next = tem->next->next;
cur->next->next = tem;
cur = tem;
}
return fake_head.next;
}
};
递归法:
/**
* 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* succ = head->next;
head->next = swapPairs(head->next->next);
succ->next = head;
return succ;
}
};