180ms non recursive Java solution, using fake header, O(n) space


  • 1
    S
    public class Solution {
        public ListNode swapPairs(ListNode head) {
            ListNode preHead = new ListNode(-1);
            ListNode ptr = preHead;
            if(head == null) return null;
            if(head.next == null) return head;
            preHead.next = head;
            head = head.next;
            while(ptr.next != null && ptr.next.next != null) {
                ListNode next = ptr.next;
                ptr.next = ptr.next.next;
                next.next = ptr.next.next;
                ptr.next.next = next;
                ptr = next;
            }
            return head;
        }
    }

  • 0
    S

    Actually your code is O(1) space. And the question is asking for constant space also.


  • 0
    S

    Thanks for reminding, I check the question again and it's my mistake...


  • 0
    N

    mistake twice then right......luck boy


  • 0
    S

    ?i dont understand what you mean


Log in to reply
 

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