Assignment:
Write Java code that displays all of the objects in a stack s in the order in which they were pushed onto the stack. After all of the objects are displayed, s should have the same contents as when you started.
This is what I have so far:
public class Main
{
public static void main(String[] args)
{
Stack s = new Stack();
System.out.println("Insertion of 10 characters in s");
for (int i = 0; i < 10; i++)
{
int x = 32 + (int)(Math.random()*95);
System.out.println(x + " --> " + (char)x);
s.push((char)x);
s.pop();
}
System.out.println("\nDisplaying elements of stack s:");
for (int i = 0; i < 10; i++)
{
s.peek();
System.out.println("Item at the top: " + s);
s.pop();
}
}
}
//week 6 - lecture: Stack class
public class Stack
{
public Stack()
{
size = 100;
list = new char[size];
n = 0;
}
public Stack(int s)
{
size = s;
list = new char[size];
n = 0;
}
public void push(char c)
{
list[n] = c;
n++;
}
public void pop()
{
n--;
}
public char peek()
{
return list[n-1];
}
public boolean isEmpty()
{
return n==0;
}
private char[] list;
private int size;
private int n;
}

New Topic/Question
Reply




MultiQuote





|