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

Swap Nodes in Pairs

2015-06-10 22:22 543 查看
题目:

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.

思路:

两两进行,交换,注意设定好交换节点,防止链表断裂,或是采用递归形式



代码:

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 *first=head;
ListNode *pre=head;;
ListNode *second;

second=first->next;//单独处理头结点
first->next=second->next;
second->next=first;
head=second;
pre=first;
first=first->next;

while(first!=NULL&&first->next!=NULL)//注意&&的前后顺序
{
second=first->next;
first->next=second->next;
second->next=first;
pre->next=second;
pre=first;
first=first->next;
}
return head;
}
ListNode *swapPairs2(ListNode *head) //递归法,清晰明了
{
if(!head) return NULL;

if(head->next)
{
ListNode *temp = head, *nextHead = head->next->next;
head = head->next;
head->next = temp;
head->next->next = swapPairs(nextHead);
}
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: