Simple solution with dummy initial node


  • 0
    A
    public class Solution {
        public ListNode SwapPairs(ListNode head) {
            ListNode initial = new ListNode(-1) { next = head };
            ListNode curr = initial;
            
            while (curr?.next?.next != null) {
                var temp = curr.next;
                curr.next = curr.next.next;
                temp.next = curr.next.next;
                curr.next.next = temp;
                
                curr = temp;
            }
            
            return initial.next;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.