Skip to content

Commit 62636dc

Browse files
author
wangzheng
committed
08_stack
1 parent 704a1af commit 62636dc

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package stack;
2+
3+
/**
4+
* 基于链表实现的栈。
5+
*
6+
* Author: Zheng
7+
*/
8+
public class StackBasedLinkedList {
9+
private Node top = null;
10+
11+
public void push(int value) {
12+
Node newNode = new Node(value, null);
13+
// 判断是否栈空
14+
if (top == null) {
15+
top = newNode;
16+
} else {
17+
newNode.next = top;
18+
top = newNode;
19+
}
20+
}
21+
22+
/**
23+
* 我用-1表示栈中没有数据。
24+
*/
25+
public int pop() {
26+
if (top == null) return -1;
27+
int value = top.data;
28+
top = top.next;
29+
return value;
30+
}
31+
32+
public void printAll() {
33+
Node p = top;
34+
while (p != null) {
35+
System.out.print(p.data + " ");
36+
p = p.next;
37+
}
38+
System.out.println();
39+
}
40+
41+
private static class Node {
42+
private int data;
43+
private Node next;
44+
45+
public Node(int data, Node next) {
46+
this.data = data;
47+
this.next = next;
48+
}
49+
50+
public int getData() {
51+
return data;
52+
}
53+
}
54+
}

0 commit comments

Comments
 (0)