Search code examples
javainterfacestackjava-ioprintstream

How i print a stack using printStream argument in java?


This is a method from an interface which i have to implement in another class and i don't know how to create it. I have to print the stack using linkedList with printStream argument. Inside the class Node(for linkedList) i have a method getObject().

import java.io.PrintStream;
import java.util.NoSuchElementException;

public interface StringStack {


    public boolean isEmpty();

    public void push(String item);

    public String pop() throws NoSuchElementException;

    public String peek() throws NoSuchElementException;

    /**
     * print the contents of the stack, starting from the item
         * on the top,
     * to the stream given as argument. For example, 
     * to print to the standard output you need to pass System.out as
     * an argument. E.g., 
     * printStack(System.out); 
     */
    public void printStack(PrintStream stream);

    public int size();

}




public class StringStackImpl implements StringStack {
    private Node head;
....
    public void printStack(PrintStream stream) {???}

}

Solution

  • Not sure how is the structure of your stack but this should do:

      Node node = head; // top of the stack
    
      while(node != null){
         stream.println(node.value);
         stream.flush();
         node = node.next;
      }