10.6 LAB: Implement a stack using an array
Given main() complete the Stack class by writing the methods push() and pop(). The stack uses an array of size 5 to store elements. The command Push followed by a positive number pushes the number onto the stack. The command Pop pops the top element from the stack. Entering -1 exits the program.
Ex. If the input is
Push 1 Push 2 Push 3 Push 4 Push 5 Pop -1
the output is
Stack contents (top to bottom): 1 Stack contents (top to bottom): 2 1 Stack contents (top to bottom): 3 2 1 Stack contents (top to bottom): 4 3 2 1 Stack contents (top to bottom): 5 4 3 2 1 Stack contents (top to bottom): 4 3 2 1
PushPopStack.java
import java.util.Scanner;
public class PushPopStack {
public static void main (String[] args) {
Scanner scnr = new Scanner(System.in);
Stack stack = new Stack(5);
String action; // Push or Pop
int numInput; // Integer value to push
action = scnr.next();
while (!action.equals("-1")) {
if (action.equals("Push")) {
numInput = scnr.nextInt();
stack.push(numInput);
System.out.println("Stack contents (top to bottom):");
stack.printStack();
}
else if (action.equals("Pop")) {
stack.pop();
System.out.println("Stack contents (top to bottom):");
stack.printStack();
}
action = scnr.next();
}
}
}
Stack.java
public class Stack {
private int topElement;
int size;
int [] array;
public Stack(int arraySize) {
size = arraySize;
array = new int[size];
topElement = -1;
}
// TODO: Write a method to push a value into the stack
// TODO: Write a method to pop the top value from the stack
public void printStack() {
int i;
for(i = topElement; i >= 0; --i) {
System.out.println(array[i]);
}
System.out.println();
}
}
public class Stack { private int topElement; int size; int[] array; public Stack(int arraySize) { size = arraySize; array = new int[size]; topElement = -1; } public void push(int num) { if (topElement < size - 1) { array[topElement + 1] = num; topElement++; } } public int pop() { if (topElement > -1) { int result = array[topElement]; topElement--; return result; } else { return -1; } } public void printStack() { int i; for (i = topElement; i >= 0; --i) { System.out.println(array[i]); } System.out.println(); } }
Get Answers For Free
Most questions answered within 1 hours.