1. 程式人生 > >Swap Nodes in Pairs(交換鏈表中的節點)

Swap Nodes in Pairs(交換鏈表中的節點)

bsp mod spa and color con chang ati ext

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; }

Swap Nodes in Pairs(交換鏈表中的節點)