swap-nodes-in-pairs

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.

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

My solution:

/**
 * 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
        if (head == null) {
            return null;
            
        }
        
        ListNode dummy = new ListNode(0);
        ListNode last = dummy;
        //make sure the list has more than one node
        while(head != null && head.next != null) {
            
            // save the third node
            ListNode temp = head.next.next;
            // connect the last and the second node
            last.next = head.next;
            // connect the second and the first, then they are swapped
            last.next.next = head;
            // update the next pointer of the end 
            head.next = null;
            // make the head to the remaining nodes
            head = temp;
            // update the last node
            last = last.next.next;
        }
        //if there are one node left, add it to the end
        //if head is null, it still works
        last.next = head;
        
        return dummy.next;
    }
}


public class Solution {
    /**
     * @param head a ListNode
     * @return a ListNode
     */
    public ListNode swapPairs(ListNode head) {
        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;
            
            // move to next pair
            head = n1;
        }
        
        return dummy.next;
    }
}

你可能感兴趣的:(swap-nodes-in-pairs)