Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone, please I need help with the runtime error that I'm getting while trying to iterate over a stack that is backed by a Linkedlist using a ListIterator. I want to use a stack to reverse an array. I've used a for loop to iterate over the array and it worked but I also want to use a ListIterator to do the same thing.

import java.util.LinkedList;
import java.util.ListIterator;

public class ReverseAnArrayUsingStack {

    public static void main(String[] args) {

        int[] intArray = {1, 2, 3, 4, 5};

        LinkedList<Integer> stack = new LinkedList<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(5);

        for (int i = stack.size(); i > 0; i--) {
            System.out.println(stack.pop());
		 }
		 
		printStack(intArray);
		
	   }
	   
	public static void printStack(int[] array) {

        ListIterator<Integer> iterator = stack.listIterator();
        while (stack.hasNext()) {
            System.out.println(stack.next());
        }
    }

    }


The error is coming from the stack.listIterator() in the printStack method on this line =>
ListIterator<Integer> iterator = stack.listIterator();

My IDE is suggesting that I should create a field called stack. There is a problem with
stack.listIterator();
as the "stack" can't access listIterator.
Please how can I resolve this issue ? Thanks for any help.

What I have tried:

public static void printStack(int[] array) {

    ListIterator<Integer> iterator = stack.listIterator();
    while (stack.hasNext()) {
        System.out.println(stack.next());
    }
}
Posted
Updated 28-Oct-22 13:54pm

1 solution

The variable stack is local to the main method - meaning it's defined there and is therefore only known there. If you want to use it in the printStack method you need to pass it there.

Note that in the loop above the call to printStack you pop all the values off of stack. If you then pass stack to it, stack will be empty.

Also, you say the for loop iterates over the array. It does not. It iterates over stack. What's in stack has no connection to the array other than that you push the same values in it as were initialized into the array. Instead you should iterate the array to fill stack, like so:
for (int i = 0; i < intArray.length; i++) {
    stack.push(intArray[i]);
}

Now stack will have the same values to which intArray is initialized, whatever their values or order may be.
 
Share this answer
 
v2
Comments
UT7 8-Nov-22 11:27am    
@FreedMalloc, sorry for the late response. Thanks a lot for your answer, got it.
FreedMalloc 8-Nov-22 11:31am    
You're very welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900