Given a linked list, swap every two adjacent nodes and return its head.
Given 1->2->3->4, you should return the list as 2->1->4->3.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode run = dummy;
while(run != null && run.next != null){
helper(run);
run = run.next.next;
}
return dummy.next;
}
public void helper(ListNode head){
if(head.next.next == null) return;
ListNode cur = head.next;
head.next = cur.next;
cur.next = head.next.next;
head.next.next = cur;
}
}