My Solution Space O(1) and One Pass


  • 0

    '''
    /**

    • Definition for singly-linked list.

    • public class ListNode {

    • int val;
      
    • ListNode next;
      
    • ListNode(int x) { val = x; }
      
    • }
      */
      class Solution {
      public ListNode swapPairs(ListNode head) {
      if (head == null || head.next == null) return head;

       ListNode dummyHead = new ListNode(0);
       dummyHead.next = head;
       ListNode curr = dummyHead;
       
       while(curr.next!=null && curr.next.next!=null)
       {
           ListNode first = curr.next;
           ListNode second = curr.next.next;
           first.next = second.next;
           second.next = curr.next;
           curr.next = second;
           curr = curr.next.next;
       }
       
       return dummyHead.next;
      

      }
      }
      '''


Log in to reply
 

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