【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;}