0% found this document useful (0 votes)
12 views

Stack Implementation Using Array

How to implement stack via array

Uploaded by

Amita Barwan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Stack Implementation Using Array

How to implement stack via array

Uploaded by

Amita Barwan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Main.

java 12/6/2020 1:41 PM

1 /*
2 Stack implementation using Array.
3 Intialize size of arrray, stack
4 pointer(sp) and stack array.
5 */
6
7 class Stack
8 {
9 int s = 3;
10 int sp=-1;
11 int stack[] = new int[s];
12
13 /*
14 Push method is used to insert an
15 element in a stack.
16 */
17
18 void push(int val)
19 {
20 if (sp==s-1)
21 {
22 System.out.println("Stack overflow");
23 }
24 else
25 {
26 sp++;
27 stack[sp] = val;
28 System.out.println(val+" pushed into stack");
29 }
30 }
31

Page 1 of 4
Main.java 12/6/2020 1:41 PM

32 /*
33 Pop method is used to remove an
34 element in a stack.
35 */
36
37 void pop()
38 {
39 if (sp==-1)
40 {
41 System.out.println("Stack underflow");
42 }
43 else
44 {
45 int val = stack[sp];
46 System.out.println(val+" pop out from stack");
47 sp--;
48 }
49 }
50
51 /*
52 Peek method is used to show the top
53 element of a stack if stack is not
54 empty.
55 */
56
57 void peek()
58 {
59 if (sp<0)
60 {
61 System.out.println("Stack underflow");
62 }

Page 2 of 4
Main.java 12/6/2020 1:41 PM

63 else
64 {
65 int val = stack[sp];
66 System.out.println("Peek element is "+val);
67 }
68 }
69
70 /*
71 Display method is used to show the all
72 element of a stack.
73 */
74
75 void display()
76 {
77 if(sp==-1)
78 {
79 System.out.println("Stack underflow");
80 }
81 else
82 {
83 for (int i=sp; i>=0; i--)
84 {
85 System.out.println("|" +stack[i]+ "|");
86 }
87 }
88 }
89 }
90
91 // Main class
92 class Main
93 {

Page 3 of 4
Main.java 12/6/2020 1:41 PM

94 public static void main(String[] args)


95 {
96 Stack st = new Stack();
97 st.push(10);
98 st.push(20);
99 st.push(30);
100 st.display();
101 st.pop();
102 st.peek();
103 }
104 }
105

Page 4 of 4

You might also like