forked from guokaide/algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathListStack.java
More file actions
74 lines (62 loc) · 1.5 KB
/
ListStack.java
File metadata and controls
74 lines (62 loc) · 1.5 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
package stack;
public class ListStack<T> implements Stack<T> {
private Node top = null;
// T(N)=O(1)
@Override
public boolean push(T item) {
Node newNode = new Node(item, null);
// 需要判断栈是否为空
if (top == null) {
top = newNode;
} else {
newNode.next = top;
top = newNode;
}
return true;
}
// T(N)=O(1)
@Override
public T pop() {
if (top == null) {
return null;
}
Node tmp = top;
top = top.next;
tmp.next = null; // 释放删除的top
return (T) tmp.getData();
}
// T(N)=O(1)
@Override
public T peek() {
if (top == null) {
return null;
}
return (T) top.getData();
}
public static class Node<T> {
private T data;
private Node next;
public Node(T data, Node next) {
this.data = data;
this.next = next;
}
public T getData() {
return this.data;
}
}
public static void main(String[] args) {
ListStack<String> stack = new ListStack<>();
stack.push("A");
stack.push("B");
stack.push("C");
stack.push("D");
System.out.println(stack.peek());
stack.pop();
System.out.println(stack.peek());
stack.pop();
stack.pop();
stack.pop();
stack.pop();
System.out.println(stack.peek());
}
}