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.
难度:中等
看到题目第一反应就是递归,每次递归负责交换头两个结点,优点是思路简单,缺点是递归会叠加栈。
/**
* 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==nullptr||head->next==nullptr) return head;//当为空,或只有一个结点时不需要进行交换
ListNode* after=swapPairs(head->next->next);
ListNode* second=head->next;
head->next=after;
second->next=head;
return second;
}
};
用迭代法,交换每对结点,还得更改其先驱结点
/**
* 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* preHead=new ListNode(0);
ListNode* preNode=preHead;
preNode->next=head;//先驱结点
while(head)
{
ListNode* second=head->next;
if(!second) break;
preNode->next=second;
head->next=second->next;
second->next=head;
//更新先驱和head
preNode=head;
head=head->next;
}
return preHead->next;
}
};
迭代法会快一点