-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.java
More file actions
50 lines (35 loc) · 855 Bytes
/
Stack.java
File metadata and controls
50 lines (35 loc) · 855 Bytes
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
package StackArray;
public class Stack<Item> {
private Item[] stack;
private int numberOfItems;
public Stack(){
this.stack = ( Item[] ) new Object[1];
}
public void push(Item item){
if( numberOfItems == this.stack.length ){
resize(2*this.stack.length);
}
this.stack[numberOfItems++] = item;
}
public Item pop(){
Item itemToPop = this.stack[--numberOfItems];
if( numberOfItems > 0 && numberOfItems == this.stack.length/4 ){
resize(this.stack.length/2);
}
return itemToPop;
}
public boolean isEmpty(){
return this.numberOfItems == 0;
}
public int size(){
return this.numberOfItems;
}
// O(n)
private void resize(int capacity) {
Item[] stackCopy = ( Item[] ) new Object[capacity];
for(int i=0;i<numberOfItems;i++){
stackCopy[i]=this.stack[i];
}
this.stack = stackCopy;
}
}