您的位置:首页 > Web前端 > Node.js

LeetCode--Swap Nodes in Pairs

2017-07-26 11:32 435 查看
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.

方法一:递归法。每次交换前两个,并递归调用交换后面的,交换后面的时候也是先交换前两个,直到不能交换。

/**
* 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* newhead=head->next;
head->next=swapPairs(newhead->next);
newhead->next=head;
return newhead;
}
};


方法二:定义一个辅助的头结点和头指针(会发现很方便)。直接正向思维,交换每相邻的两个节点,记录第三个节点更新给当前的头指针的下一个即可,这里的头指针每次都是更新为待交换两个节点前的那个。

/**
* 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 dummy(0);
ListNode *cur=&dummy;
while(head&&head->next){
ListNode *next=head->next->next;
cur->next=head->next;
cur=cur->next;
cur->next=head;
cur=cur->next;
head->next=NULL;
head=next;
}
if(head) cur->next=head;
return dummy.next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: