美文网首页
24. 两两交换链表中的节点

24. 两两交换链表中的节点

作者: Andysys | 来源:发表于2019-12-29 00:21 被阅读0次
    //递归
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        ListNode next = head.next;
        head.next = swapPairs(next.next);
        next.next = head;
        return next;
    }

    //迭代
    public ListNode swapPairs2(ListNode head) {
        ListNode temp = new ListNode(0);
        temp.next = head;
        ListNode pre = temp;
        ListNode first, second;
        while (pre.next != null && pre.next.next != null) {
            first = pre.next;
            second = pre.next.next;
            pre.next = second;
            first.next = second.next;
            second.next = first;
            pre = first;
        }
        return temp.next;
    }

相关文章

网友评论

      本文标题:24. 两两交换链表中的节点

      本文链接:https://www.haomeiwen.com/subject/jebeoctx.html