Leetcode OJ 24 Swap Nodes in Pairs [Medium]
来源:互联网 发布:开发一个刷赞软件 编辑:程序博客网 时间:2024/05/18 02:27
Leetcode OJ 24 Swap Nodes in Pairs [Medium]
题目描述:
Given alinked 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.
Youralgorithm should use only constant space. You may not modify the values in thelist, only nodes itself can be changed.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(intx) { val = x; }
* }
*/
题目理解:
给定一个链表,交换相邻的节点,返回新链表的头指针。
算法应只使用恒定空间,不要修改链表中的值,只有节点本身可以修改。
测试用例:
功能测试:给定链表的节点个数是偶数;给定链表的节点个数是奇数;
边界测试:给定链表头指针是null;给定链表只有一个头节点;链表有2个节点;链表有3个节点;链表有4个节点;
分析:
循环的方法:
1. 维护两个指针,one和nextone,one指向相邻两个节点中的第一个节点,nextone指向下一个相邻两个节点中的第一个节点;
2. 首先处理特殊输入:当头节点是null或者只有一个头节点时,直接返回头节点;
3. 新链表的头节点是原头节点的下一个节点;
4. 当nextone不为空且nextone.next不为空时,循环操作:相邻节点的第二个节点(one.next)指向相邻节点的第一个节点(one);相邻节点的第一个节点(one)指向下一个相邻节点的第二个节点(nextone.next);更新one和nextone;
5. 结束循环后,这时剩下3个或2个节点没有处理(nextone!=null&& nextone.next==null和 nextone==null),此时都将相邻节点的第二个节点(one.next)指向相邻节点的第一个节点(one)不变,与循环中不同的是,相邻节点的第一个节点(one)指向下一个相邻节点的第一个节点(nextone)
递归的方法:
6. 相邻两个节点的第一个节点指向后面下一个相邻两个节点的结果;相邻两个节点的第二个节点指向第一个节点;
7. 返回的是相邻两个节点的第二个节点;
8. 处理边界:如果相邻两个节点都是空或一个是空,则返回第一个节点;
解答一(循环):
class Solution { public ListNode swapPairs(ListNode head) { if(head == null) return null; if(head.next == null) return head; ListNode one = head; head = one.next; ListNode nextone = one.next.next; while(nextone != null && nextone.next != null){ one.next.next = one; one.next = nextone.next; one = nextone; nextone = one.next.next; } one.next.next = one; one.next = nextone; return head; }}
解答二(递归):
public class Solution { public ListNode swapPairs(ListNode head) { if ((head == null)||(head.next == null)) return head; ListNode n = head.next; head.next = swapPairs(head.next.next); n.next = head; return n; }}
- Leetcode OJ 24 Swap Nodes in Pairs [Medium]
- [Leetcode 24, Medium] Swap Nodes in Pairs
- LeetCode OJ-24-Swap Nodes in Pairs
- LeetCode-24-Swap Nodes in Pairs(链表)-Medium
- LeetCode OJ:Swap Nodes in Pairs
- LeetCode OJ - Swap Nodes in Pairs
- [LeetCode OJ]Swap Nodes in Pairs
- LeetCode OJ Swap Nodes in Pairs
- 【LeetCode OJ 024】Swap Nodes in Pairs
- [LeetCode OJ]Swap Nodes in Pairs
- [LeetCode] 024. Swap Nodes in Pairs (Medium) (C++/Python)
- LeetCode刷题——Swap Nodes in Pairs(Medium)
- [LeedCode OJ]#24 Swap Nodes in Pairs
- [Leetcode 24, Medium] Swap Nodes in Pair
- LeetCode(24)Swap Nodes in Pairs
- [LeetCode 24] Swap Nodes in Pairs
- [leetcode 24]Swap Nodes in Pairs
- LeetCode | #24 Swap Nodes in Pairs
- 谈MVVM
- 最大子串和
- 约束布局constraint-layout导入失败的解决方案
- HDU5867-Water problem
- pgsql 计算时间差的秒数
- Leetcode OJ 24 Swap Nodes in Pairs [Medium]
- Unity3D 关于模型变形技术代码实现
- Swift 中的方法(函数)
- python-7
- Ruby:字符串处理函数
- 新版Bintray-极简上传Library到JCenter
- 删除文本中行尾空格-linux
- CentOS 7 上安装 Redis 服务器的方法
- lintcode带最小值操作的栈