您的位置:首页 > Web前端 > Node.js

【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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: