Skip to content

Commit bcd2887

Browse files
committed
custom implementation of simple stack
1 parent 18b9dd4 commit bcd2887

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package datastructure.simplestack;
2+
3+
public class App {
4+
public static void main(String... args) {
5+
System.out.println("custom stack implementation");
6+
CustomStack theStack = new CustomStack(5);
7+
theStack.push(13);
8+
theStack.push(23);
9+
theStack.push(33);
10+
theStack.push(43);
11+
theStack.push(53);
12+
theStack.push(63);
13+
theStack.push(73);
14+
theStack.push(83);
15+
System.out.println("popped out value "+ theStack.pop());
16+
17+
theStack.printStack();
18+
theStack.pop();
19+
theStack.printStack();
20+
21+
theStack.peak();
22+
23+
// empty out the stack
24+
while (!theStack.isEmpty()){
25+
System.out.println("popped out value "+ theStack.pop());
26+
}
27+
}
28+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package datastructure.simplestack;
2+
3+
public class CustomStack {
4+
5+
int top = -1;
6+
int maxSize = 10;
7+
long[] stackArray;
8+
9+
public CustomStack(int maxSize){
10+
this.maxSize = maxSize;
11+
stackArray = new long[maxSize];
12+
}
13+
14+
public void push(int value) {
15+
if(isFull()){
16+
System.out.println("Cannot add more as stack is already full ");
17+
}else {
18+
top++;
19+
stackArray[top] = value;
20+
}
21+
}
22+
23+
public int pop(){
24+
if(isEmpty()){
25+
System.out.println("Cannot pop more since stack is empty");
26+
return -1;
27+
}else {
28+
int old_top = top;
29+
top--;
30+
return (int) stackArray[old_top];
31+
}
32+
}
33+
34+
public int peak(){
35+
System.out.println("top element of stack is");
36+
return (int) stackArray[top];
37+
}
38+
39+
public boolean isEmpty(){
40+
return top == -1;
41+
}
42+
43+
public boolean isFull(){
44+
return top == (maxSize-1);
45+
}
46+
47+
public void printStack(){
48+
System.out.println("current values in stack are ");
49+
for(int i=0; i<=top;i++){
50+
System.out.println(stackArray[i]);
51+
}
52+
}
53+
}

0 commit comments

Comments
 (0)