LeetCode 24 Swap Nodes in Pairs
来源:互联网 发布:数据安全责任承诺书 编辑:程序博客网 时间:2024/06/11 18:01
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.
使用遍历。交换前两个节点后,往下两个节点循环前,要记录上个节点哦,否则会丢节点呢。
对于链表操作,别想太多,就是该怎么办就怎么办,凭感觉写就好了。
public ListNode swapPairs(ListNode head) {if (head == null || head.next == null) return head;ListNode result = head.next;ListNode pre = new ListNode(-1);while (head != null && head.next != null) {ListNode even = head.next;head.next = even.next;even.next = head;pre.next = even;pre = head;head = head.next;}return result;}
另外,可以使用递归:
public ListNode swapPairs(ListNode head) {if (head == null || head.next == null) return head;ListNode even = head.next;head.next = swapPairs(even.next);even.next = head;return even;}
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
- 理解Cookie和Session机制
- 环形(蛇形)矩阵
- html pc、手机、微信端自适应,app推广下载页面
- Oracle出现1069错误的解决方法
- HTML属性大全
- LeetCode 24 Swap Nodes in Pairs
- HBase——查询延迟的时间分布
- Wireshark网络分析实战笔记(三)基本信息统计工具的用法
- Android Environment 常量含义
- jls之happen-before
- iOS app内使用第三方字体
- 现代操作系统第三版课后习题解答
- JAVA中使用FTPClient实现文件上传下载
- 欢迎使用CSDN-markdown编辑器