-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.java
More file actions
123 lines (112 loc) · 2.45 KB
/
Stack.java
File metadata and controls
123 lines (112 loc) · 2.45 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package datastructure.stackandqueue.stack;
/**
* The type Stack.
*
* @param <V> the type parameter
*/
public class Stack<V> {
private int maxSize;
private int top;
private V[] array;
private int currentSize;
/**
* Instantiates a new Stack.
*
* @param maxSize the max size
*/
/*
Java does not allow generic type arrays. So we have used an
array of Object type and type-casted it to the generic type V.
This type-casting is unsafe and produces a warning.
Comment out the line below and execute again to see the warning.
*/
@SuppressWarnings("unchecked")
public Stack(int maxSize) {
this.maxSize = maxSize;
this.top = -1; //initially when stack is empty
array = (V[]) new Object[maxSize];//type casting Object[] to V[]
this.currentSize = 0;
}
/**
* Gets current size.
*
* @return the current size
*/
public int getCurrentSize() {
return currentSize;
}
/**
* Gets max size.
*
* @return the max size
*/
//returns the maximum size capacity
public int getMaxSize() {
return maxSize;
}
/**
* Is empty boolean.
*
* @return the boolean
*/
//returns true if Stack is empty
public boolean isEmpty() {
return top == -1;
}
/**
* Is full boolean.
*
* @return the boolean
*/
//returns true if Stack is full
public boolean isFull() {
return top == maxSize - 1;
}
/**
* Top v.
*
* @return the v
*/
//returns the value at top of Stack
public V top() {
if (isEmpty())
return null;
return array[top];
}
/**
* Push.
*
* @param value the value
*/
//inserts a value to the top of Stack
public void push(V value) {
if (isFull()) {
System.err.println("Stack is Full!");
return;
}
array[++top] = value; //increments the top and adds value to updated top
currentSize++;
}
/**
* Pop v.
*
* @return the v
*/
//removes a value from top of Stack and returns
public V pop() {
if (isEmpty())
return null;
currentSize--;
return array[top--]; //returns value and top and decrements the top
}
/**
* Peek v.
*
* @return the v
*/
public V peek(){
if(isEmpty())
return null;
return array[top];
}
}