Swap Nodes in Pairs
2015-08-12 16:26
471 查看
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given
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)
return NULL;
if(head->next==NULL)
return head;
ListNode *p1=head;
ListNode *p2=head->next;
p1->next=p2->next;
p2->next=p1;
ListNode *temp,*pre=p1;
for(ListNode *cur=p1->next;cur!=NULL;cur=cur->next){
temp=cur->next;
if(temp!=NULL){
cur->next=temp->next;
temp->next=cur;
pre->next=temp;
pre=cur;
}
}
return p2;
}
};
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)
return NULL;
if(head->next==NULL)
return head;
ListNode *p1=head;
ListNode *p2=head->next;
p1->next=p2->next;
p2->next=p1;
ListNode *temp,*pre=p1;
for(ListNode *cur=p1->next;cur!=NULL;cur=cur->next){
temp=cur->next;
if(temp!=NULL){
cur->next=temp->next;
temp->next=cur;
pre->next=temp;
pre=cur;
}
}
return p2;
}
};
相关文章推荐
- Leetcode#24||Swap Nodes in Pairs
- [LeetCode] Populating Next Right Pointers in Each Node II
- datanode起不起来
- Nodejs的上传模块formidable
- [LeetCode] Populating Next Right Pointers in Each Node
- node.js + Express 学习之 环境配置篇
- 117. Populating Next Right Pointers in Each Node II
- 116. Populating Next Right Pointers in Each Node
- 利用promise写出更加优美的nodejs程序
- 在 Node.js 中用 Q 实现 Promise – Callback 之外的另一种选择
- NodeJs教程
- Node.js async in practice: When to use what?
- 在Node.js中使用promise摆脱回调金字塔
- Node.js 常见面试题
- Leetcode#19||Remove Nth Node From End of List
- node.js--Less
- [转]Nodejs开发框架Express4.x开发手记
- LeetCode题解:Delete Node in a Linked List
- Remove Nth Node From End of List
- HtmlParser初探--使用Nodefilter和Visitor进行网页分析