0
点赞
收藏
分享

微信扫一扫

力扣24 两两交换链表中的节点

归零者245号 2022-03-12 阅读 77

方法一:非递归

public ListNode swapPairs(ListNode head){
        ListNode res=new ListNode(0);
        res.next=head;
        ListNode cur=res;
        while (cur.next!=null&&cur.next.next!=null){
            ListNode start=cur.next;
            ListNode end=cur.next.next;
            cur.next=end;
            start.next=end.next;
            end.next=start;
            cur=start;
        }
        return res.next;
    }

方法二:递归

public ListNode swapPairs(ListNode head){
        if(head==null||head.next==null) return head;
        ListNode node=head.next;
        head.next=swapPairs(node.next);
        node.next=head;
        return node;
    }
举报

相关推荐

0 条评论