LeetCode 24 Swap Nodes in Pair
来源:互联网 发布:易赛软件 编辑:程序博客网 时间:2024/06/06 11:06
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.
解题思路:这是一个简单的链表操作题,只需要注意开始以及为奇数链表情况下结尾的问题。
代码如下:
- public ListNode swapPairs(ListNode head) {
- ListNode l1 = head;
- ListNode l0 = null;
- ListNode l2 = null;
- if(head==null||head.next==null){
- return head;
- }
- int index =0;
- while(l1!=null){
- ListNode l3 = l1;
- ListNode l4 = l1.next;
- if(l1.next == null){
- return l2;//奇数情况 前面置换完后直接返回
- }
- l3.next = l4.next;
- l4.next = l3;
- l1 = l3.next;
- if(index!=0){
- l0.next = l4;
- }
- l0 = l3;
- if(index ==0){
- l2 = l4;
- index++;
- }
- }
- return l2;
- }
- class Solution {
- public:
- ListNode* swapPairs(ListNode* head) {
- ListNode *p=head;
- int tmp;
- while(p&&p->next){
- tmp=p->val;
- p->val=p->next->val;
- p->next->val=tmp;
- p=p->next->next;
- }
- return head;
- }
- };
0 0
- [Leetcode 24, Medium] Swap Nodes in Pair
- LeetCode 24 Swap Nodes in Pair
- LeetCode(24)Swap Nodes in Pairs
- [LeetCode 24] Swap Nodes in Pairs
- [leetcode 24]Swap Nodes in Pairs
- LeetCode | #24 Swap Nodes in Pairs
- [Leetcode 24 链表]Swap Nodes in Pairs
- leetcode 24 Swap Nodes in Pairs
- 【leetcode】【单链表】【24】Swap Nodes in Pairs
- Leetcode 24 Swap Nodes in Pairs
- Swap Nodes in Pairs - LeetCode 24
- LeetCode 24 - Swap Nodes in Pairs
- leetcode 24 -- Swap Nodes in Pairs
- LeetCode 24:Swap Nodes in Pairs
- leetcode-24Swap Nodes in Pairs
- leetcode 24: Swap Nodes in Pairs
- Leetcode#24 Swap Nodes in Pairs
- LeetCode 24: Swap Nodes in Pairs
- 启动hadoop时报错,nodemanager running as process 6410. Stop it first.解决方法
- C++集合操作之集合交集:std::set_intersection
- 建筑建模学习笔记3——Vray渲染及PS修图
- C++实现CVPR2010 LLC(局部约束线性编码)
- NYOJ 814 又见拦截导弹
- LeetCode 24 Swap Nodes in Pair
- Openstack部署工具总结
- 威佐夫博奕
- NET下RabbitMQ实践[示例篇]
- webService学习记录-02
- hdu 5093 Battle ships(二分图匹配)
- 博弈汇集
- Post,同步实现登陆验证(2)
- 数据库初步