Swap Nodes in Pairs

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

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

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

    public ListNode swapPairs(ListNode head) {
        ListNode Head = new ListNode(0);
        Head.next = head;
        ListNode pre = Head;
        ListNode cur = pre.next;
        while (cur!=null&&cur.next!=null){
            ListNode next = cur.next.next;
            ListNode tail = cur.next;
            tail.next = cur;
            cur.next = next;
            pre.next = tail;
            pre = cur;
            cur = next;
        }
        return Head.next;
    }
posted @ 2017-10-20 13:16  binryang  阅读(96)  评论(0)    收藏  举报