【Leetcode】24. Swap Nodes in Pairs
来源:互联网 发布:mac网络加速器 编辑:程序博客网 时间:2024/06/18 14:57
方法一:
思路:
(1)p1指向空,p2指向头节点,p3指向头结点的下一节点。
(2)遍历整个链表直到p3为空。
(3)每次遍历,将p2的next指向p3的next,再将p3的next指向p2,若p1为空,则头指针指向p3,否则将p1的next指向p3。
(4)每次遍历后,将p1指向p2,若p1为空,直接返回head,否则,将p2指向p1的next,若p2为空,直接返回head,否则,将p3指向p2的next,继续下一次遍历。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode swapPairs(ListNode head) { if (head == null || head.next == null) return head; ListNode p1 = null, p2 = head, p3 = head.next; while (p3 != null) { p2.next = p3.next; p3.next = p2; if (p1 == null) head = p3; else p1.next = p3; p1 = p2; if (p1 == null) return head; else { p2 = p1.next; if (p2 != null) p3 = p2.next; else return head; } } return head; }}
Runtime:5ms
方法二:递归
思路:
(1)交换前2个节点。
(2)交换除去前2个节点外的后续节点组成的链表,返回新的头结点p。
(3)将交换后的前两个节点接到p链表上,最终链表的头结点为p2。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode swapPairs(ListNode head) { if (head == null || head.next ==null) return head; ListNode p1 = head, p2 = p1.next; ListNode p = swapPairs(p2.next); p1.next = p; p2.next = p1; return p2; }}
Runtime:4ms
1 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
- 理解droupout
- Oracle Form 问题集锦 - Oracle JInitiator版本太旧(FRM-92095)
- 欢迎使用CSDN-markdown编辑器
- 动态规划思考2
- 多表查询
- 【Leetcode】24. Swap Nodes in Pairs
- 一个null引发的SharedPreference惨案
- Android adb获取屏幕分辨率
- 通过Java反射调用方法
- "应用程序无法正常启动(0xc000007b)。请单击“确定”关闭应用程序。”
- SQL数据表字段类型与属性总结(DDL)
- 动态规划思考3
- 学什么?
- 使用rpm -q mysql 出现 package mysql is not installed