【leetcode】24. Swap Nodes in Pairs
2017-08-06 11:34
281 查看
题目描述
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; }
相关文章推荐
- LeetCode 24. Swap Nodes in Pairs
- 24.[Leetcode]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 ---java
- **LeetCode 24. Swap Nodes in Pairs
- leetcode_24. Swap Nodes in Pairs C++
- 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(11)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 -- JavaScript 代码
- LeetCode 24. Swap Nodes in Pairs (Python)
- Leetcode 24. Swap Nodes in Pairs