SwapPairs_24

https://leetcode-cn.com/problems/swap-nodes-in-pairs/

image.png

(图片来源https://leetcode-cn.com/problems/swap-nodes-in-pairs/

日期 是否一次通过 comment
2020-02-17

notice:

  1. 起点竟然是dummy

// cur 是reverse的起点
    public ListNode swapPairsN(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode curNode = dummy;

        while (curNode.next != null && curNode.next.next != null) {
            ListNode first = curNode.next;
            ListNode second = curNode.next.next;
            first.next = second.next;
            second.next = first;

            curNode.next = second;
            curNode = first;  // 最容易的错的地方
        }

        return dummy.next;
    }

递归

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;
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容