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

Leetcode Swap Nodes in Pairs

2016-03-02 09:16 543 查看
递归做法:

/**
* 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 *next = head->next;
head->next = swapPairs(next->next);
next->next = head;
return 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) {
ListNode*extra = new ListNode(-1);
extra->next = head;
ListNode *preP=extra;
ListNode *p = head;
ListNode *q;
while(p!=NULL&&p->next!=NULL){
q=p->next;
//开始交换
p->next = q->next;
q->next = p;
preP->next = q;//交换完毕
preP=p;
p=preP->next;
}
return extra->next;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: