[LeetCode]24. Swap Nodes in Pairs
来源:互联网 发布:北京大学博士待遇 知乎 编辑:程序博客网 时间:2024/06/15 17:30
题目描述: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.
解题思路1:题目要求交换相邻的链表节点。
使用递归交换相邻的两个节点,当当前节点或下一个节点为空时停止递归。
public ListNode swapPairs(ListNode head) { if(head==null||head.next==null){ return head; } ListNode temp = head.next; head.next = swapPairs(head.next.next); temp.next = head; return temp; }
解题思路2:设置一个跟踪节点,每次移动两步,依次交换相邻节点。
public ListNode swapPairs2(ListNode head) { if(head==null||head.next==null){ return head; } ListNode dummyNode = new ListNode(0); dummyNode.next = head; ListNode current = dummyNode; while(current.next!=null&¤t.next.next!=null){ ListNode first = current.next; ListNode second = current.next.next; first.next = second.next; second.next = first; current.next = second; current = current.next.next; } return dummyNode.next; }
阅读全文
0 0
- [LeetCode]24.Swap Nodes in Pairs
- 24. Swap Nodes in Pairs Leetcode Python
- 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
- 24. Swap Nodes in Pairs LeetCode
- 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
- LeetCode 24. Swap Nodes in Pairs
- saltstack的SSH使用--Roster的配置使用
- java面试总结
- Visual Studio 2017开发linux程序使用实例及原理简析
- 16. 3Sum Closest
- JDK7中LinkedBlockingQueue源码解析
- [LeetCode]24. Swap Nodes in Pairs
- flexbox 笔记
- HDU 5933
- hdu 1150 Machine Schedule(二分匹配,匈牙利算法)
- Postgres:pg_basebackup物理备份与还原
- 理解执行环境、作用域链和活动对象 (转载)
- C语言中sizeof对数组和对指针操作的不同,以及sizeof中表达式赋值问题
- Java:String和Date、Timestamp之间的转换
- ccfcsp 201709-1 打酱油