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

2023-12-21 22:45:02

?代码随想录

class Solution {
    // 举例子:假设两个节点 1 -> 2
    // 那么 head = 1; next = 2; next.next = null
    // 那么swapPairs(next.next),传入的是null,再下一次递归中直接返回null
    // 因此 newNode = null
    // 所以 next.next = head; => 2.next = 1; 2 -> 1
    //      head.next=  newNode; => 1.next = null; 1->null
    // 所以 2->1->null
    // 最终返回 next,即返回 2
    public ListNode swapPairs(ListNode head) {
        
        if(head == null || head.next == null)
            return head;

        ListNode next = head.next;

        ListNode newNode = swapPairs(next.next);


        next.next = head;

        head.next = newNode;

        return next;
    }
    
}

文章来源:https://blog.csdn.net/xuan__xia/article/details/135140713
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。