Java iterative solution in constant space


  • 0
    M

    time O(n), space O(1)

    public class Solution {
        public ListNode swapPairs(ListNode head) {
            if(head==null || head.next==null) return head;
            ListNode newHead = head.next;
            ListNode p=head, preHead = new ListNode(0);
            while( p!=null ){
                preHead.next = swap(p);
                preHead = p;
                p = p.next;
            }
            return newHead;
        }
        private ListNode swap(ListNode head){
            if(head==null || head.next==null) return head;
            ListNode nextNode = head.next;
            ListNode nextHead = head.next.next;
            nextNode.next = head;
            head.next = nextHead;
            return nextNode;
        }
    }
    

Log in to reply
 

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