Skip to content

Commit b732dde

Browse files
author
phyex0
committed
Stack added.
1 parent 681a112 commit b732dde

File tree

2 files changed

+78
-6
lines changed

2 files changed

+78
-6
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package com.company.DataStructures;
2+
3+
/*
4+
* Stack:
5+
* Inserting = o(1)
6+
* Removing = o(1)
7+
* Peeking = o(1)
8+
* Checking capacity = o(1)
9+
*
10+
* In stack, first in, last out. Due to structure, you cannot take the item which is bottom first.
11+
*
12+
* */
13+
14+
public class Stack {
15+
private int[] myArray;
16+
private int size;
17+
private int index =-1;
18+
19+
//Constructor of the stack.
20+
public Stack(int size) {
21+
this.size = size;
22+
myArray = new int[size];
23+
}
24+
25+
// Checking the stack about being empty.
26+
public boolean isEmpty(){
27+
if(index ==-1){
28+
System.out.println("Stack is empty!");
29+
return true;
30+
}
31+
return false;
32+
33+
}
34+
35+
//Checking the stack about being full.
36+
public boolean isFull(){
37+
if(index+1 ==size){
38+
System.out.println("Stack is full!");
39+
return true;
40+
}
41+
return false;
42+
}
43+
44+
//Inserting data.
45+
public void push(int val){
46+
if(!isFull())
47+
myArray[++index]=val;
48+
}
49+
50+
//Removing data.
51+
public int pop(){
52+
if(!isEmpty())
53+
return myArray[index--];
54+
return -1;
55+
}
56+
57+
//Returning last item of the stack but it won't be removed.
58+
public int peek(){
59+
if(!isEmpty())
60+
return myArray[index];
61+
return -1;
62+
}
63+
64+
//returns the current size of the stack.
65+
public int getSize(){
66+
return index;
67+
}
68+
}

src/com/company/Main.java

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,22 @@
11
package com.company;
22

3-
import com.company.Algorithms.BubbleSort;
4-
import com.company.Algorithms.LinearSearch;
5-
import com.company.DataStructures.LinkedList;
3+
import com.company.DataStructures.Stack;
64

75
public class Main {
86

97
public static void main(String[] args) {
108
// write your code here
11-
int[] arr = new int[]{10,9,9,8,7,5,4,3,2,1};
12-
BubbleSort.bubbleSort(arr);
9+
Stack myStack = new Stack(5);
1310

14-
System.out.println(LinearSearch.linearSearch(arr,10));
11+
for(int i=0;i<5;i++){
12+
myStack.push(i*10);
13+
System.out.println(myStack.peek());
14+
}
15+
myStack.push(20);
1516

17+
for(int i=0;i<5;i++)
18+
System.out.println(myStack.pop());
19+
System.out.println(myStack.pop());
1620

1721

1822
}

0 commit comments

Comments
 (0)