-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayStack.java
More file actions
78 lines (64 loc) · 2.12 KB
/
Copy pathArrayStack.java
File metadata and controls
78 lines (64 loc) · 2.12 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
public class ArrayStack<E> implements Stack<E> {
private E[] data = (E[])(new Object[10]); // create an object of array, then cast to type E
private int size = 0;
public boolean isEmpty() {
if (size == 0)
return true;
else
return false;
}
// Adds an element to the end of the array
public void push(E newValue) {
if (size== data.length) {
// Make a new larger array to hold the list1's data
E[] newList = (E[])(new Object[data.length * 2]);
// Copy all existing elements of data into newData
for (int i = 0; i < data.length; i++) {
newList[i] = data[i];
}
// Point the old data reference to newData
data = newList;
}
data[size] = newValue;
size++; // increment size by 1
}
// Removes the node from list and returns the data that was in the node
public E pop() {
if (!isEmpty()) {
E dataToDelete = data[size-1];
size--;
data[size] = null;
return dataToDelete;
}
else
return null;
}
// Returns (but does not remove) the element at the top of the stack
public E peek() {
if (!isEmpty()) {
E dataToReturn = data[size-1];
return dataToReturn;
}
else
return null;
}
// Print each element of the stack from bottom to top
public String toString() {
String result = "ArrayList object (size = " + size + ", capacity = " + data.length + "), elements:\n";
for (int i = 0; i < data.length; i++) {
result += " " + data[i] + "\n";
}
return result;
}
public static void main(String[] args) {
Stack<Integer> test = new ArrayStack<>();
for (int i = 1; i < 5; i++) {
test.push(i);
}
System.out.println(test);
System.out.println("Removed data : " + test.pop());
System.out.println(test);
System.out.println("Peeked: " + test.peek());
System.out.println(test);
}
}