-
Notifications
You must be signed in to change notification settings - Fork 0
/
StackImplementation.java
65 lines (55 loc) · 1.31 KB
/
StackImplementation.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**********************************************************************
*
* The class ArrayStack implements the Stack using an array to
* hold the items.
*
* @author Pallavi Tilloo
*************************************************************************/
class ArrayStack<T> implements StackInterface<T>
{
private T[] stackItems;
private int topIndex, stackSize;
public ArrayStack(int capacity)
{
@SuppressWarnings("unchecked")
T[] temp = (T[]) new Object[capacity];
stackItems = temp;
topIndex = -1;
stackSize = 0;
}
// Adds item to stack
public void push(T item)
{
topIndex++;
if(topIndex == stackItems.length) topIndex = 0;
stackItems[topIndex] = item;
stackSize++;
}
// Removes item from stack
public T pop()
{
T returnValue = stackItems[topIndex];
topIndex--;
if (topIndex == stackItems.length) topIndex = 0;
stackSize--;
return returnValue;
}
// Returns item at top
public T peek()
{
return stackItems[topIndex];
}
// Returns true iff the stack is empty
public boolean isEmpty()
{
return stackSize == 0;
}
// Removes all items from stack
public void clear()
{
for (int i = 0; i < stackItems.length; i++)
stackItems[i] = null;
topIndex = -1;
stackSize = 0;
}
}