Leetcode 24 Swap Nodes in Pairs
来源:互联网 发布:SSL协议所使用的端口是 编辑:程序博客网 时间:2024/06/03 19:11
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.
Solution1
- 每一次处理两个节点,主要注意的是处理过程中暂存好后面的节点。
public class Solution { public ListNode swapPairs(ListNode head) { ListNode dummy = new ListNode(-1); dummy.next = head; ListNode prev = dummy; while(prev.next!=null&&prev.next.next!=null){ ListNode temp1 = prev.next;//暂存好第一个节点 prev.next = prev.next.next; ListNode temp2 = prev.next.next;//暂存好第二个节点 prev.next.next = temp1; temp1.next = temp2; prev = temp1; } return dummy.next; }}
Solution2
- 递归解法,显得更加清晰易懂。但一般不太提倡递归,因为会有隐形的栈空间调用。
public class Solution { public ListNode swapPairs(ListNode head) { if(head==null||head.next==null) return head; ListNode first = head; ListNode second = head.next; first.next = swapPairs(second.next); second.next = first; return second; }}
0 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
- Linux守护进程
- ORA-27054 RAC NFS 映射
- fragment嵌套,viewpager嵌套 不能正确显示
- 欢迎使用CSDN-markdown编辑器
- 【php】在Windows2003下的IIS配置php5.4
- Leetcode 24 Swap Nodes in Pairs
- 关系型数据库范式
- Gym 100187B - A Lot of Joy
- Java介绍+注释+环境变量笔记-第1天
- fragment嵌套viewpager嵌套 关于不能正常显示问题
- C++多态性:虚函数的调用原理
- 【Util】iText,iTextAsian,中文显示
- C++输入输出流格式控制
- hdu 5265 技巧题 O(nlogn)求n个数中两数相加取模的最大值