leetcode-24 Swap Nodes in Pairs
来源:互联网 发布:js url base64编码 编辑:程序博客网 时间:2024/05/21 06:30
问题描述
地址:https://leetcode.com/problems/swap-nodes-in-pairs/
描述:
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.
翻译:给出一个linked list,交换两个相邻的node后返回head
问题解析
初步想法:
(1)如果想交换节点位置,首先我们需要两个指针,一个标记当前及诶点(current),一个标记当前节点的下一个节点(next)
(2)交换current和next的next节点即可
然而这样直接交换显然会有个问题
解析代码
public class SwapNodesinPairs2 { public static void main(String[] args) { ListNode listNode = ListNode.init(); ListNode result = swapPairs(listNode); System.out.println("1"); } public static ListNode swapPairs(ListNode head) { ListNode current = head; if(current == null){ return head; } ListNode next = head.next; if(next == null){ return head; } //需要注意的地方1 将表头重置到第二个节点,否则表会断 //比方说 1->2->3->4 如果不重置表头最终得到的结果将会是 1->3->4 head = next; //tmp用来记录上一次交换前末尾节点的位置 ListNode tmp = null; while (current != null && next != null) { current.next = next.next; next.next = current; if (tmp != null) { tmp.next = next; } tmp = current; current = current.next; if (current != null) { next = current.next; } } return head; }}
1 0
- 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
- LeetCode(24) Swap Nodes in Pairs
- [Leetcode 24, Medium] Swap Nodes in Pairs
- 【C/C++开发】__stdcall,__cdecl,__fastcall的区别
- JDK1.7 深入理解 LinkedHashMap
- IOS 省市区三级联动
- android开发中handler的各种用法实践总结
- Git 与 SVN 区别
- leetcode-24 Swap Nodes in Pairs
- 项目访问跳转
- Android-属性动画
- Servlet的请求转发和重定向
- 263. Ugly Number
- 【小组】探空气球项目的分工与目标
- Android-Fragment 切换属性动画
- 意外断电开库触发ORA-01207
- Tomcat:基础安装和使用教程