Swap Nodes in Pairs--LeetCode
来源:互联网 发布:点击访问fc2最新域名 编辑:程序博客网 时间:2024/06/18 12:26
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.
思路:将链表拆分,然后再合并
List *swapPairs(List *head) { if(head == NULL || head->next == NULL) return head; List* ji=head; List* ou = head->next; List* temp1,*temp2; List* l1= head; List* l2 = head->next; temp1 = l2->next; while(temp1 != NULL) { temp2 = temp1->next; l1->next = temp1; l2->next = temp2; l1 = temp1; l2 = temp2; if(l2 !=NULL) temp1 = l2->next; else temp1 = NULL; } if(l1 != NULL) l1->next =NULL; if(l2 != NULL) l2->next = NULL; temp1 = ou; while(temp1 != NULL&&temp1->next != NULL) { temp2 = ji->next; ji->next = temp1->next; temp1->next = ji; temp1 = ji->next; ji = temp2; } temp1->next = ji; return ou;}
上面的思路是将一个链表拆分然后再合并,这里仍然使用一个新的节点来作为指引节点来操作。
List* SwapNode(List* list){List* head=new List;head->next = list;List* cur = head;List* pre,*next;while(cur->next != NULL && cur->next->next != NULL){pre = cur->next;next = cur->next->next;cur->next = next;next = next->next;cur->next->next = pre;pre->next = next;cur = pre;}return head->next;}ps:其实问题的思路非常的简单,但是解决问题的方法决定了处理问题的简易程度,比如我们始终使用一个指针的next域来指向准备反转的一对指针的第二个指针,然后再反转这对指针即可,这里使用一个伪指针来处理这个问题非常的合适。
1 0
- LeetCode:Swap Nodes in Pairs
- LeetCode: Swap Nodes in Pairs
- [Leetcode] Swap Nodes in Pairs
- LeetCode : Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs
- Leetcode: Swap nodes in pairs
- [LeetCode]Swap Nodes in Pairs
- [LeetCode]Swap Nodes in Pairs
- LeetCode-Swap Nodes in Pairs
- LeetCode - Swap Nodes in Pairs
- LeetCode | Swap Nodes in Pairs
- 【leetcode】Swap Nodes in Pairs
- Leetcode: Swap Nodes in Pairs
- LeetCode - Swap Nodes in Pairs
- 【LeetCode】Swap Nodes in Pairs
- Leetcode: Swap Nodes in Pairs
- Leetcode Swap Nodes in Pairs
- LeetCode Swap Nodes in Pairs
- sdut2410 Mine Number
- 高效人士睡觉前做的10件事
- Android中内容观察者的使用---- ContentObserver类详解
- 简易Web服务器
- 2015年蓝桥杯省赛B组第10题--生命之树
- Swap Nodes in Pairs--LeetCode
- DataPump使用说明
- ADF中如何将两个独立的LOV实现级联
- Ubuntu 12.04 LTS 中文输入法的安装
- Android学习心得① - GridView设置分割线的一种简单方法
- undefined reference to涉及的链接问题
- Android中的Intent(一)
- 深度学习资料链接
- Ubuntu 环境安装整理