LeetCode Swap Nodes in Pairs
来源:互联网 发布:vb 向上取整 编辑:程序博客网 时间:2024/04/20 21:51
递归实现:(思路非常清晰)
public ListNode swapPairs(ListNode head) { if(head == null || head.next == null){ return head; } ListNode second = head.next; ListNode third = second.next; second.next = head; head.next = swapPairs(third); return second; }
非递归实现:
假如现在是 1->2->3->4->5->6
public ListNode swapPairs(ListNode head) { if(head==null || head.next==null){ return head; } ListNode newHead = head.next; // a = 1, b = 2 ListNode a=head, b=a.next, pre = null; while(a!=null && b!=null){ // a.next = 3 ,b.next = 1 a.next = b.next; b.next = a; if(pre!=null){ pre.next = b; } if(a.next==null) break; // 如果是奇数,下一个为空就会跳出循环,否则就会执行下面三条语句,进行交换 // b = 4, pre = 1, a = 3 b = a.next.next; pre = a; a = a.next; } 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
- RecycleView(插件式架构)使用
- 结构体的偏移量计算
- 手机分辨率
- 多线程编程
- 一个帖子学会Android开发四大组件
- LeetCode Swap Nodes in Pairs
- python 参数传递[打包与解包问题]
- zoj-3785-What day is that day?
- 进制转换
- C++第5次实验- 教师类
- linux下exit()和_exit()区别
- zoj-3782-Ternary Calculation
- mysql多实例
- Spring MVC 4 文件上传下载 Hibernate+MySQL例子 (带源码)