Skip to content

Commit bbbf63c

Browse files
committed
Move code for Stack ArrayList from Stacks.java to StackArrayList.java
1 parent 4bbc39f commit bbbf63c

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed
+94
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import java.util.ArrayList;
2+
3+
/**
4+
* This class implements a Stack using an ArrayList.
5+
*
6+
* A stack is exactly what it sounds like. An element gets added to the top of
7+
* the stack and only the element on the top may be removed.
8+
*
9+
* This is an ArrayList Implementation of a stack, where size is not
10+
* a problem we can extend the stack as much as we want.
11+
*
12+
* @author Unknown
13+
*
14+
*/
15+
public class StackArrayList{
16+
17+
/**
18+
* Main method
19+
*
20+
* @param args Command line arguments
21+
*/
22+
public static void main(String[] args) {
23+
StackArrayList myStackArrayList = new StackArrayList(); //Declare a stack of maximum size 4
24+
//Populate the stack
25+
myStackArrayList.push(5);
26+
myStackArrayList.push(8);
27+
myStackArrayList.push(2);
28+
myStackArrayList.push(9);
29+
30+
System.out.println("*********************Stack List Implementation*********************");
31+
System.out.println(myStackArrayList.isEmpty()); //will print false
32+
System.out.println(myStackArrayList.peek()); //will print 9
33+
System.out.println(myStackArrayList.pop()); //will print 9
34+
System.out.println(myStackArrayList.peek()); // will print 2
35+
System.out.println(myStackArrayList.pop()); //will print 2
36+
}
37+
38+
/** ArrayList representation of the stack */
39+
private ArrayList<Integer> stackList;
40+
41+
/**
42+
* Constructor
43+
*/
44+
public StackArrayList(){
45+
stackList = new ArrayList<>();
46+
}
47+
48+
/**
49+
* Adds value to the end of list which
50+
* is the top for stack
51+
*
52+
* @param value value to be added
53+
*/
54+
public void push(int value){
55+
stackList.add(value);
56+
}
57+
58+
/**
59+
* Pops last element of list which is indeed
60+
* the top for Stack
61+
*
62+
* @return Element popped
63+
*/
64+
public int pop(){
65+
66+
if(!isEmpty()){ // checks for an empty Stack
67+
68+
int popValue=stackList.get(stackList.size()-1);
69+
stackList.remove(stackList.size()-1); //removes the poped element from the list
70+
return popValue;
71+
}
72+
73+
System.out.print("The stack is already empty ");
74+
return -1;
75+
}
76+
77+
/**
78+
* Checks for empty Stack
79+
*
80+
* @return true if stack is empty
81+
*/
82+
public boolean isEmpty(){
83+
return stackList.isEmpty();
84+
}
85+
86+
/**
87+
* Top element of stack
88+
*
89+
* @return top element of stack
90+
*/
91+
public int peek(){
92+
return stackList.get(stackList.size()-1);
93+
}
94+
}

0 commit comments

Comments
 (0)