Labels

algorithms (22) Design Patterns (20) java (19) linux (14) Snippet (13) service mix (6) soa (4)

Recursively reverse a linked list

private static Node recurReverseLinkedList(Node firstNode) {
        if (firstNode == null || firstNode.next == null) {
            return firstNode;
        }
        
        Node secondNode = firstNode.next; // the new head node to be reversed
        firstNode.next = null; // de-link the node from the list
        Node previousFirstNode = recurReverseLinkedList(secondNode); //reverse rest
        secondNode.next = firstNode; //the second node next will be first node
        return previousFirstNode; 
    }

No comments:

Post a Comment

Search 24 Bytes

Loading...