leetcode-两两交换链表中的节点

class Solution {
    public ListNode swapPairs(ListNode head) {
        return swap(head);
    }
    public ListNode swap(ListNode leftnode){
        if(leftnode==null || leftnode.next == null){
            return leftnode;
        }
        ListNode tempnextnode = leftnode.next;
        leftnode.next = swap(leftnode.next.next);
        tempnextnode.next = leftnode;
        return tempnextnode;
    }
}

递归解决这类题的精髓就是让某一个Node的next是递归函数的返回值!

之前我的写法是在递归函数中拼装好了然后调用swap(node.next),这样会增加复杂度

发布了48 篇原创文章 · 获赞 0 · 访问量 4319

猜你喜欢

转载自blog.csdn.net/weixin_41327340/article/details/104089086