-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNonSafeStack.java
More file actions
62 lines (50 loc) · 1.17 KB
/
NonSafeStack.java
File metadata and controls
62 lines (50 loc) · 1.17 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
package example3;
import common.MStack;
public class NonSafeStack<T> implements MStack<T> {
protected class Node {
public T value;
public Node next;
public Node(T value, Node next) {
this.value = value;
this.next = next;
}
}
protected Node head = null;
protected int length = 0;
public void push(T value) {
Node node = new Node(value, head);
head = node;
length += 1;
}
public T peek() {
if (head != null)
return head.value;
else
return null;
}
public T pop() {
if (head != null) {
T result = head.value;
head = head.next;
length -= 1;
return result;
}
else
return null;
}
public void reverse() {
if (head == null) return;
Node prev = null;
Node cursor = head;
while (cursor != null) {
Node next = cursor.next;
cursor.next = prev;
prev = cursor;
cursor = next;
}
head = prev;
}
public int size() {
return length;
}
}