Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
.
public static ListNode swapPairs(ListNode head) { ListNode dummy = new ListNode(0); dummy.next = head; if(head == null || head.next == null){ return dummy.next; } ListNode c = dummy; ListNode first = head; ListNode second = head.next; while(first!=null && first.next!=null){ c.next = second; first.next = second.next; second.next = first; c = first; first = first.next; if(first!=null){ second = first.next; } } return dummy.next; }