/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null) {
return null;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy, curr = head, next = curr.next;
while(next != null) {
prev.next = next;
curr.next = next.next;
next.next = curr;
prev = curr;
curr = prev.next;
next = curr == null ? null : curr.next;
}
return dummy.next;
}
}
Time: O(n)
Space: O(1)