Akaleaf

JavaStack

Dec 9th, 2018
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.87 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class StackX {
  4.     private int maxSize;
  5.     private long[] stackArray;
  6.     private int top;
  7.     private int view;
  8.  
  9.     public StackX(int s) {
  10.         maxSize = s;
  11.         stackArray = new long[maxSize];
  12.         top = -1;
  13.         view = -1;
  14.     }
  15.  
  16.     public void push(long j) {
  17.         stackArray[++top] = j;
  18.     }
  19.  
  20.     public long pop() {
  21.         return stackArray[top--];
  22.     }
  23.  
  24.     public long view() {
  25.         return stackArray[view--];
  26.     }
  27.  
  28.     public void setViewToTop() {
  29.         view = top;
  30.     }
  31.  
  32.     public long peek() {
  33.         return stackArray[top];
  34.     }
  35.  
  36.     public boolean isEmpty() {
  37.         return (top == -1);
  38.     }
  39.  
  40.     public boolean isEmptybyView() {
  41.         return (view == -1);
  42.     }
  43.  
  44.     public boolean isFull() {
  45.         return (top == maxSize - 1);
  46.     }
  47. }
  48.  
  49. class StackApp {
  50.     public static void main(String[] args) {
  51.         Scanner in = new Scanner(System.in);
  52.         StackX theStack = new StackX(10);
  53.         int answer = 0;
  54.         while (!(answer == 3)) {
  55.             theStack.setViewToTop();
  56.             System.out.print("[");
  57.             while (!theStack.isEmptybyView()) {
  58.                 long value = theStack.view();
  59.                 System.out.print(value);
  60.                 if (theStack.isEmptybyView()) break;
  61.                 System.out.print(" ");
  62.             }
  63.             theStack.setViewToTop();
  64.             System.out.println("]");
  65.             System.out.println("1. Add element");
  66.             System.out.println("2. Remove element");
  67.             System.out.println("3. Exit");
  68.             answer = in.nextInt();
  69.             if (answer == 1) {
  70.                 System.out.print("Enter the element: ");
  71.                 theStack.push(in.nextInt());
  72.             }
  73.             if (answer == 2) {
  74.                 theStack.pop();
  75.             }
  76.         }
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment