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.

Solution:

This is an easay question.
If there are more than two nodes behind, exchange the order of the following two nodes,
and then move the http://www.lintcode.com/en/problem/swap-nodes-in-pairs/pointer 2 places.

Leetcode link
Lintcode link

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/*************************************************************************
> File Name: SwapNodesinPairs.java
> Author: Yao Zhang
> Mail: psyyz10@163.com
> Created Time: Wed 18 Nov 23:21:09 2015
************************************************************************/


public class SwapNodesinPairs{
public ListNode swapPairs(ListNode head) {
// Write your code here
ListNode dummy = new ListNode(-1);
dummy.next = head;
head = dummy;

while (head.next != null && head.next.next != null){
ListNode temp = head.next;
head.next = temp.next;
temp.next = head.next.next;
head.next.next = temp;
head = head.next.next;
}

return dummy.next;
}
}