Reverse a doubly linked list

  • + 0 comments

    Java

    Iterative

    public static DoublyLinkedListNode reverse(DoublyLinkedListNode llist) {
    	DoublyLinkedListNode newHead = null;
    	while(llist != null){
    		DoublyLinkedListNode next = llist.next;
    		llist.next = newHead;
    		llist.prev = next;
    		newHead = llist;
    		llist = next;
    	}
    	return newHead;
    }
    

    Recursive:

    public static DoublyLinkedListNode reverse(DoublyLinkedListNode llist) {
    	return helper(null, llist);
    }
    
    private static DoublyLinkedListNode helper(DoublyLinkedListNode prev, DoublyLinkedListNode node){
    	if(node == null)
    		return prev;
    	DoublyLinkedListNode next = node.next;
    	node.next = prev;
    	node.prev = next;
    	return helper(node, next);
    }