-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathStackBasedOnLinkedList.java
More file actions
61 lines (53 loc) · 1.3 KB
/
StackBasedOnLinkedList.java
File metadata and controls
61 lines (53 loc) · 1.3 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
package struct.stack;
/**
* 基于单链表实现的栈
*
* @param <T>
*/
public class StackBasedOnLinkedList<T> {
private Node<T> top;
public void push(T data) {
Node newNode = new Node(data, null);
if (top == null) {
top = newNode;
} else {
newNode.next = top;
top = newNode;
}
}
public T pop() {
if (top == null) {
return null;
}
T value = top.data;
top = top.next;
return value;
}
public void printAll() {
Node temp = top;
while (temp != null) {
System.out.print(temp.data + ",");
temp = temp.next;
}
System.out.println();
}
public static void main(String[] args) {
StackBasedOnLinkedList<Integer> list = new StackBasedOnLinkedList<>();
list.push(1);
list.push(2);
list.push(3);
list.printAll();
System.out.println(list.pop());
System.out.println(list.pop());
System.out.println(list.pop());
System.out.println(list.pop());
}
public static class Node<T> {
private T data;
private Node next;
public Node(T data, Node next) {
this.data = data;
this.next = next;
}
}
}