Reverse a doubly linked list

  • + 0 comments

    Java 15 O(n)

    public static DoublyLinkedListNode reverse(DoublyLinkedListNode llist) {
            DoublyLinkedListNode current = llist;
            DoublyLinkedListNode prev = null;
    
            while (current != null) {
                DoublyLinkedListNode nextNode = current.next;
                current.next = prev;
                current.prev = nextNode; // swap prev and next pointers
                prev = current;
                current = nextNode;
            }
    
            //prev points to the new head of the reversed list
            return prev;
        }