[LintCode] Swap Nodes in Pairs

java 4 2016-02-29 13:03
女装

Problem

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

Example

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

Solution

public class Solution {

public ListNode swapPairs(ListNode head) {
    // Write your code here
    if (head == null) {
        return null;
    }
    ListNode dummy = new ListNode(0);
    dummy.next = head;
    ListNode pre = dummy;
    
    while (pre.next != null && pre.next.next != null) {
        //存储第三个结点
        ListNode next = pre.next.next.next;
        //简单的swap p.next和p.next.next换了一下
        ListNode temp = pre.next;
        pre.next = pre.next.next;
        pre.next.next = temp;
        //连接后面的链表
        temp.next = next;
        //更新pre的位置
        pre = temp;
    }
    return dummy.next;
}

}

女装
文章评论