2 solutions - use two extra pointers & recursive
Solution 1 use two extra pointers
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode res=new ListNode(-1);
res.next=head;
ListNode p=res;
ListNode q=head;
while(q!=null && q.next!=null){
p.next=q.next;
q.next=p.next.next;
p.next.next=q;
p=q;
q=q.next;
}
return res.next;
}
}
Solution 2 recursive
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null){
return null;
}
if(head.next == null){
return head;
}
ListNode tmp = head.next;
head.next = swapPairs(tmp.next);
tmp.next = head;
return tmp;
}
}
```