Sort by

recency

|

699 Discussions

|

  • + 0 comments

    Reversing a doubly linked list is all about carefully swapping next and prev for each node, one wrong move and the whole chain breaks. How did you handle the pointer swap without losing track of the list?

  • + 0 comments

    Simple java solution TC-O(N) SC-O(1)

    public static DoublyLinkedListNode reverse(DoublyLinkedListNode llist) {
            if(llist == null || llist.next == null){
                return llist;
            }
            DoublyLinkedListNode last = null;
            DoublyLinkedListNode curr = llist;
            
            while(curr!=null){
                last = curr.prev;
                curr.prev = curr.next;
                curr.next = last;
                curr = curr.prev;
            }
            return last.prev;
        }
    
    }
    
  • + 0 comments

    My Java 8 Solution

    public static DoublyLinkedListNode reverse(DoublyLinkedListNode llist) {
            DoublyLinkedListNode reversedList = null, current = llist;
            
            while (current != null) {
                DoublyLinkedListNode temp = new DoublyLinkedListNode(current.data);
                
                if (reversedList == null) {
                    reversedList = temp;
                } else {
                    temp.next = reversedList;
                    reversedList.prev = temp;
                    reversedList = reversedList.prev;
                }
                current = current.next;
            }
            
            return reversedList;
        }
    
  • + 0 comments

    PSA: DO NOT USE KOTLIN

    You cannot pass using Kotlin due to this issue, which still remains today.

  • + 0 comments

    My Java solution with linear time complexity and constant space complexity:

     public static DoublyLinkedListNode reverse(DoublyLinkedListNode llist) {
            //return llist if its null, indicating the llist is empty
            if(llist == null) return llist;
            
            //use a curr ptr
            DoublyLinkedListNode curr = llist;
            
            //iterate thru the llist
            while(curr != null){
                //store curr nxt in a temp var
                DoublyLinkedListNode temp = curr.next;
                curr.next = curr.prev;
                curr.prev = temp;
                
                if(temp == null) break;
                else curr = temp;
            }
            return curr;        
        }