class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) return head;
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode prevEnd = dummy;
ListNode first = prevEnd.next;
ListNode second = first.next;
while (first != null && second != null) {
ListNode nextNode = second.next;
prevEnd.next = second;
second.next = first;
first.next = nextNode;
prevEnd = first;
first = prevEnd.next;
if (first == null) break;
second = first.next;
if (second == null) break;
}
return dummy.next;
}
}