Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return its head.
Example
Given1->2->3->4, you should return the list as2->1->4->3.
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy, p = head;
while(p != null && p.next != null) {
ListNode second = p.next;
p.next = second.next;
second.next = pre.next;
pre.next = second;
pre = p;
p = p.next;
}
return dummy.next;
}