24 Swap Nodes in Pairs
1. Question
2. Implementation
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode curNode = dummy;
ListNode first = null, second = null;
while (curNode.next != null && curNode.next.next != null) {
first = curNode.next;
second = curNode.next.next;
first.next = second.next;
second.next = curNode.next;
curNode.next = second;
curNode = first;
}
return dummy.next;
}
}3. Time & Space Complexity
Last updated