Swap Nodes in Pairs(交换链表中的节点)

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list's nodes, only nodes itself may be changed.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

    public static ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        if(head == null || head.next == null){
            return dummy.next;
        }
        ListNode c = dummy;
        ListNode first = head;
        ListNode second = head.next;
        
        while(first!=null && first.next!=null){
            c.next = second;
            first.next = second.next;
            second.next = first;
            
            c = first;
            first = first.next;
            if(first!=null){
                second = first.next;
            }
            
        }
        
        return dummy.next;
    }

猜你喜欢

转载自www.cnblogs.com/wkcode/p/10410519.html