简体   繁体   中英

Java remove an element from linked list recursion

For this assignment given to me, I am supposed to move through a linked list of size 1,000,000 iteratively and recursively. I have the iterative part down but I am confused on the recursive part. I have the concept down but I have told my teacher that I cannot recursively do it because I will inevitably get a stack overflow error. He says I should not be getting that problem but I am totally stuck. Any tips would be great as I have no idea what I am doing wrong.

public static void main(String[] args) {

    System.out.println("Please enter how many random numbers you want to generate: ");
    Scanner prompt = new Scanner(System.in);
    int amount = prompt.nextInt();

    Random rnd = new Random();
    System.out.println("Creating list...");
    for (int i = 0; i < amount; i++) {
        randomList.add(rnd.nextInt(100));
    }
    System.out.println("Going through list...");
    iterateNumbers();

    long startTimeRec = System.nanoTime();
    recursiveNumbers(randomList);
    long elapsedTimeRec = System.nanoTime() - startTimeRec;
    double seconds = (double)elapsedTimeRec / 1000000000.0;
    System.out.println("Recursively, the function took " + seconds + " seconds.");

    prompt.close();

}
//create the linked list
public static LinkedList<Integer> randomList = new LinkedList<Integer>();

private static void iterateNumbers() {

    long startTime = System.nanoTime();
    for (int i = 0; i < randomList.size(); i++) {
        randomList.remove();
    }
    long elapsedTime = System.nanoTime() - startTime;
    double seconds = (double)elapsedTime / 1000000000.0;
    System.out.println("Iteratively, the function took " + seconds + " seconds.");
}

private static void recursiveNumbers(LinkedList<Integer> current) {     

    if (current.isEmpty() == true) {
        return;
    } else {
        current.removeFirst();
        recursiveNumbers(current);
    }
}

}

In the iterative version , you should pass in the index at the remove.

randomList.remove(i);

And should you not also repopulate the linked list before you call the recursive method?

    for (int i = 0; i < amount; i++) {
    randomList.add(rnd.nextInt(100));
}

Not too sure about the Java implementation of the Linked List. Tried looking it up there. Is there a isEmpty() method? Or should you try:

if(current.size() < 1) 
    return;

It's not very hard to understand. When you run your program, the stack area is not enough,so you have a error.

You can try to add the space of the stack.

run the program with the following arguments:

-Xss1280m

It means create the stack with 1280MB, and you will see the result like this:


在此输入图像描述

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