【leetcode】24. Swap Nodes in Pairs
来源:互联网 发布:ar学校 软件下载 编辑:程序博客网 时间:2024/05/16 07:47
题目描述
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.输入的链表是不是空链表或者是只有一个元素的链表,如果是的话,直接返回head;
2.交换两个相邻节点,实现这一步,我定义了p、q两个变量;
3.因为上一步执行完之后,还要考虑交换后的前一个节点与其之前的节点连接的问题,因而我定义了第三个变量pre_node;
4.在对链表中前两个节点执行操作后,剩下的节点放在一个while循环里执行,直到最后没有节点或者只有一个节点时跳出循环。
代码
我按照下面的代码打败了17.9%的Java,很不理想
public ListNode swapPairs(ListNode head) { if (head == null || head.next == null) { return head; } ListNode p, q, pre_node; p = head; q = p.next; head = q; p.next = q.next; q.next = p; pre_node = p; while (p.next != null && p.next.next != null) { p = pre_node.next; q = p.next; p.next = q.next; q.next = p; pre_node.next = q; pre_node = p; } return head;}然后参考了讨论区中其他人的代码,采用递归的方法试了一下,70.56%
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;}
阅读全文
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
- Hdu-4666 Hyperspace(曼哈顿距离)
- 再探reverse_iterator和iterator的关系
- 智能电视盒·路由·手机·家用电脑
- java开发环境的搭建
- 乐观锁和悲观锁的区别
- 【leetcode】24. Swap Nodes in Pairs
- Shell中字符串的切割、拼接、比较、替换
- android MVP + dagger2 + Retrofit + Rxjava+okhttp android基础项目框架搭建(1)--之Dagger2引入
- cocos2d_x事件交互处理
- Servlet 使用介绍(2)
- V4L2摄像头应用流程
- Python文件操作
- springboot统一异常处理器
- 【博览网】面向对象编程下——第一周课程笔记