Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way I can combine these two methods?

Currently I'm creating a method to reverse a linkedlist in java, but it requires two methods:

public void reverse(){
    reverse(head);
}

private void reverse(Node h){
    if(h.next==null){
        System.out.print(h.data+" ");
        return;
    }

    reverse(h.next);
    System.out.print(h.data+" ");   
}

This way I call the reverse method with 0 parameters, which then calls the other reverse method. Is there any way to make them 1 method without changing the other aspects of my LinkedList class?

Thanks in advance!

like image 970
idude Avatar asked Dec 18 '22 21:12

idude


1 Answers

It is very common to have a public method calling a private recursive method with extra parameter(s). See the source code for Arrays.deepToString(Object[]) for an example of this.

However, in your case it may be better to avoid recursion completely. One problem with recursion is that you are only able to nest method calls to a certain depth before you get a StackOverflowError.

An alternative is to use loops instead. The following would work:

public void reverse(){
    List<Node> nodes = new ArrayList<>();
    for (Node n = head; n != null; n = n.next)
        nodes.add(n);
    for (int i = nodes.size() - 1; i >= 0; i--)
        System.out.print(nodes.get(i).data + " ");
}
like image 99
Paul Boddington Avatar answered Jan 11 '23 04:01

Paul Boddington