Swap Nodes in Pairs

来源:互联网 发布:win7仿mac任务栏 编辑:程序博客网 时间:2024/06/03 21:43

Given a linked list, swap every two adjacent nodes and return its head.
样例
Given 1->2->3->4, you should return the list as 2->1->4->3.

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    /**     * @param head a ListNode     * @return a ListNode     */    public ListNode swapPairs(ListNode head) {        // Write your code here        ListNode dummy = new ListNode(0);        dummy.next = head;        head = dummy;        while(head.next != null && head.next.next != null){            ListNode n1 = head.next, n2 = head.next.next;            //head->n1->n2...            //=>head->n2->n1...            head.next = n2;            n1.next = n2.next;            n2.next = n1;            head = n1;        }        return dummy.next;    }}
0 0