Is there a way to combine these two methods?

I am currently creating a method to modify a linked list in java, but this 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+" ");   
}

Thus, I call the inverse method with 0 parameters, which then calls another inverse method. Is there a way to make them one method without changing other aspects of my LinkedList class?

Thanks in advance!

+4
source share
4 answers

Very often there is a public method that calls a private recursive method with additional parameters. See the source code for an example Arrays.deepToString(Object[]).

. , , StackOverflowError.

. :

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 + " ");
}
+5

, , . :

public void reverse( Node... nodes )
{
    Node h;
    if( nodes.length == 0 )
        h = head;
    else
    {
        assert nodes.length == 1;
        h = nodes[0];
    }

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

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

, , Node public, . ( , , , .)

.

+3

, , , , ArrayList :

, . , node, . , , , , node. , , .

public void reverse() {
    int length = length();
    Node [] nodes = new Node[length];
    Node currentNode = head;

    int i = 0;
    // Populate the array
    while(currentNode != null)
    {
        nodes[i] = currentNode;
        currentNode = currentNode.next;
        i++;
    }

    // Iterate backwards to print the array
    for(int j = length -1; j >= 0; j--)
    {
        System.out.println(nodes[i] + " ");
    }
}
+2

. "" . Node Type Node, . , Node, Index of 0 ( ).

Node, , , , default 0 ( , ). arrayInfo [] array, , -, headerInfo [] ( ) Node h. args [] .

public void reverse(Node... headerInfo){
    Node h = 0;
    if (headerinfo.length != 0) { h = headerInfo[0]; } 

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

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

reverse() reverse (head)

EDIT:

Whops... :)

+1

Source: https://habr.com/ru/post/1617802/


All Articles