Skip to content

Commit ab8c2a7

Browse files
Merge pull request #3 from RianGallagher/master
Added an array implementation of a stack
2 parents 4e14eb0 + 816116e commit ab8c2a7

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

data_structures/Stacks.java

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
*A stack is exactly what it sounds like. An element gets added to top of the stack and only the element on the top may be removed.
3+
*This is an example of an array implementation of a Stack. So an element can only be added/removed from the end of the array.
4+
*In theory stacks have no fixed size, but with an array implementation it does.
5+
*/
6+
class Stack{
7+
private int maxSize;
8+
private int[] stackArray;
9+
private int top;
10+
11+
public Stack(int size){ //Constructor
12+
maxSize = size;
13+
stackArray = new int[maxSize];
14+
top = -1;
15+
}
16+
17+
public void push(int value){ //Adds an element to the top of the stack
18+
top++;
19+
stackArray[top] = value;
20+
}
21+
22+
public int pop(){ //Removes the top element of the stack and returns the value you've removed
23+
return stackArray[top--];
24+
}
25+
26+
public int peek(){ //Returns the element at the top of the stack
27+
return stackArray[top];
28+
}
29+
30+
public boolean isEmpty(){ //Returns true if the stack is empty
31+
return(top == -1);
32+
}
33+
34+
public boolean isFull(){ //Returns true if the stack is full
35+
return(top+1 == maxSize);
36+
}
37+
public void makeEmpty(){ //Doesn't delete elements in the array but if you call
38+
top = -1; //push method after calling makeEmpty it will overwrite previous values
39+
}
40+
}
41+
//Example
42+
public class Stacks{
43+
public static void main(String args[]){
44+
Stack myStack = new Stack(4); //Declare a stack of maximum size 4
45+
//Populate the stack
46+
myStack.push(5);
47+
myStack.push(8);
48+
myStack.push(2);
49+
myStack.push(9);
50+
51+
System.out.println(myStack.isEmpty()); //will print false
52+
System.out.println(myStack.isFull()); //will print true
53+
System.out.println(myStack.peek()); //will print 9
54+
System.out.println(myStack.pop()); //will print 9
55+
System.out.println(myStack.peek()); // will print 2
56+
}
57+
}

0 commit comments

Comments
 (0)