Swap Nodes in Pairs
2015-06-14 15:32
597 查看
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.
Solutions:
三个指针,开始的时候new一个节点,其next指向head,结束的时候delete掉。
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head==NULL) {
return head;
}
ListNode *prev=NULL;
if(head->next==NULL)
return head;
ListNode *ret=new ListNode(0);
prev=ret;
prev->next=head;
ListNode *p1=head, *p2=p1->next;
while(1) {
prev->next=p2;
p1->next=p2->next;
p2->next=p1;
prev=p1;
if(p1->next==NULL)
break;
p1=prev->next;
if(p1->next==NULL)
break;
p2=p1->next;
}
prev=ret;
ret=ret->next;
delete prev;
return ret;
}
};
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.
Solutions:
三个指针,开始的时候new一个节点,其next指向head,结束的时候delete掉。
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head==NULL) {
return head;
}
ListNode *prev=NULL;
if(head->next==NULL)
return head;
ListNode *ret=new ListNode(0);
prev=ret;
prev->next=head;
ListNode *p1=head, *p2=p1->next;
while(1) {
prev->next=p2;
p1->next=p2->next;
p2->next=p1;
prev=p1;
if(p1->next==NULL)
break;
p1=prev->next;
if(p1->next==NULL)
break;
p2=p1->next;
}
prev=ret;
ret=ret->next;
delete prev;
return ret;
}
};
相关文章推荐
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- C#数据结构与算法揭秘二
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- C++实现汉诺塔算法经典实例
- PHP实现克鲁斯卡尔算法实例解析
- C#常见算法面试题小结
- JavaScript 组件之旅(二)编码实现和算法
- JavaScript数据结构和算法之图和图算法