简体   繁体   中英

reverse double linked list using recursion

I am writing program to reverse double linked list using recursion. I know how to implement iteratively. but stuck in recursion.

Here is what I have

public static Node reverseRecurseDoubleLinkedList(Node node){
        if (node==null || node.next==null)
            return node;
        Node newNode = reverseRecurseDoubleLinkedList(node.next);
        node.next.next=node;
        node.next=null;
        node.prev=newNode;
        return newNode;
    }

I see the prev pointers are not set properly. but next pointers are in fact correct.

Thanks

In general, one way to simplify thinking about recursive code is to only consider the guarantees that are offered when a recursive call is complete. You then need to check that these guarantees hold in the basic case that stops recursion (eg empty list, or list with a single node), and that they are maintained with each additional recursive call.

There are a few issues in the code provided:

  • the condition that stopped recursion did not handle correctly the situations when node.next == null . The node.prev field should have been set to null in that case.

  • the newNode variable name may cause some confusion. It represents the new head of the reversed list (which was the tail of the initial list). I renamed it to newHead .

  • related to the point above, the assignment node.prev=newNode; is not correct -- we do not want the prev of each node to point to the head of the new list.

After incorporating these aspects, the code below correctly reverses the list:

public static Node reverseRecurseDoubleLinkedList(Node node) {
    if (node == null) {
        return node;
    }

    if (node.next == null) {
        node.prev = null;
        return node;
    }

    Node newHead = reverseRecurseDoubleLinkedList(node.next);
    node.next.next = node;
    node.prev = node.next;
    node.next = null;

    return newHead;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM