Question
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 .
Solution
Java
/**
* 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 || head.next == null) {
return head;
}
ListNode next = head.next;
head.next = swapPairs(head.next.next);
next.next = head;
return next;
}
}