fork download
  1.  
  2. class Stack {
  3. // size of the stack
  4. static final int MAX = 1000;
  5. int top;
  6. int a[] = new int[MAX]; // Maximum size of Stack
  7.  
  8. //check if the stack is empty if top is -1 then stack is empty else not
  9. boolean isEmpty()
  10. {
  11. return (top < 0);
  12. }
  13. // constructor for the Stack Class
  14. {
  15. top = -1;
  16. }
  17.  
  18.  
  19. boolean push(int x)
  20. {
  21. // if stack is already full
  22. if (top >= (MAX - 1)) {
  23. System.out.println("Stack Overflow");
  24. return false;
  25. }
  26. else {
  27. a[++top] = x;
  28. System.out.println(x + " pushed into stack");
  29. return true;
  30. }
  31. }
  32.  
  33. int pop()
  34. {
  35. // if stack is empty
  36. if (top < 0) {
  37. System.out.println("Stack Underflow");
  38. return 0;
  39. }
  40. else {
  41. int x = a[top--];
  42. return x;
  43. }
  44. }
  45.  
  46. int peek()
  47. {
  48. // if stack is empty
  49. if (top < 0) {
  50. System.out.println("Stack Underflow");
  51. return 0;
  52. }
  53. else {
  54. int x = a[top];
  55. return x;
  56. }
  57. }
  58. }
  59.  
  60. // Driver code
  61. class Main {
  62. public static void main(String args[])
  63. {
  64. Stack s = new Stack();
  65. s.push(10);
  66. s.push(20);
  67. s.push(30);
  68. System.out.println("top element of the stack is " + s.peek());
  69. System.out.println(s.pop() + " Popped from stack");
  70. System.out.println("top element of the stack is " + s.peek());
  71. }
  72. }
  73.  
Success #stdin #stdout 0.14s 35868KB
stdin
Standard input is empty
stdout
10 pushed into stack
20 pushed into stack
30 pushed into stack
top element of the stack is 30
30 Popped from stack
top element of the stack is 20