C# simple solution


  • 0
    F
    public class Solution {
        public ListNode SwapPairs(ListNode head) {
            if(head == null || head.next == null) return head;
            
            var p = head;
            var tail = head;
            var isFirstNode = true;     
            while(p != null && p.next != null)
            {
                var temp = p.next;
                tail.next = temp;
                tail = p;
                p.next = temp.next;
                temp.next = p;
                p = p.next;
    
                if(isFirstNode)
                {
                    head = temp;
                    isFirstNode = !isFirstNode;
                }
            }
            
            return head;
        }
    }
    

Log in to reply
 

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