LeetCode Swap Nodes in Pairs
来源:互联网 发布:淘宝店铺粉丝最多 编辑:程序博客网 时间:2024/06/06 08:52
题意:给出一个单链表,每两个一组相互交换,不能通过交换每组的值来实现
思路:
1、链表为空或者只有一个结点,不需要交换
2、有两个结点时p,q,其中q = p.next,交换用p.next = q.next,q.next = p
3、在有多于2个结点时,以4个为例,前一组交换后的结点的后继结点应该是后一组结点未交换前的第二个
具体代码如下:
class ListNode{ int val; ListNode next; ListNode(int x) { val = x;}}class Solution{ public ListNode swapPairs(ListNode head) { if (null == head || null == head.next) return head; ListNode cur = head, next = cur.next; ListNode newHead = next; cur.next = next.next; next.next = cur; if (null == cur.next) return newHead; while (cur.next.next != null) { ListNode pre = cur; cur = cur.next; next = cur.next; pre.next = next; cur.next = next.next; next.next = cur; if (null == cur.next) break; } return newHead; }}
0 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
- 解决maven打包编译出现using platform encoding GBK, i.e. build
- <ScrollView> 滚动视图的简单功能和用法
- nginx、php-fpm以及mysql运行在各个用户下的配置
- Android之eclipse NDK开发环境的搭建
- Pycharm连接Github
- LeetCode Swap Nodes in Pairs
- dataset总结
- 链接和库
- ListView的点击事件应用
- Batch Normalization导读
- 自定义拖拽IndicatorView
- post发送JSON数据(字符串、数组、字典、自定义对象)给服务器
- 手把手教你开发基于深度学习的人脸识别【考勤/签到】系统
- EditTexts实现图文混排