leetcode-24. Swap Nodes in Pairs

题目类型:链表

题意:

给出一个链表,按对交换节点,
- 常数空间
- 不能用改变节点的值的方法做,需要交换节点本身。

我的思路:迭代。两两交换,修改next等指针

效率:10%

对于当前节点first,和下一个节点second
- 记录上一次交换后的最后一个节点pre
- 因为交换后链表断裂,所以暂存second下一个节点的位置,temp = second.next;
- pre.next = second; second.next = first; first.next = temp;
- 更新pre = first,继续交换下面的节点

class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode pre = new ListNode(0);
        ListNode copy = pre;
        ListNode first = head;
        ListNode second = head.next;
        while (first != null && second != null) {
            first.next = second.next;//相当于 暂存下一个的指针
            pre.next = second;
            second.next = first;

            pre = first;
            first = first.next;
            second = (first != null) ? first.next : null;
        }
        return copy.next;
    }
}

方法二:递归

效率略高于迭代

    //方法二:递归
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode temp = head.next;// 最终结果的头指针必定是第二个节点
        head.next = swapPairs(head.next.next);
        temp.next = head;
        return temp;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值