/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummyhead = new ListNode();
dummyhead.next = head;
ListNode cur = dummyhead;
while (cur.next != null && cur.next.next != null){
ListNode temp1 = cur.next;
ListNode temp2 = cur.next.next.next;
cur.next = cur.next.next;
cur.next.next = temp1;
cur.next.next.next = temp2;
cur = cur.next.next;
}
return dummyhead.next;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if (head==null || head.next==null){
return head;
}
ListNode dummyhead = new ListNode();
dummyhead.next = head;
return swap(dummyhead,dummyhead);
}
public ListNode swap(ListNode cur,ListNode dummyhead){
if(cur.next==null || cur.next.next==null){
return dummyhead.next;
}
ListNode temp1 = cur.next;
ListNode temp2 = cur.next.next.next;
cur.next = cur.next.next;
cur.next.next = temp1;
cur.next.next.next = temp2;
return swap(cur.next.next,dummyhead);
}
}