“栈” 遵循先进后出的原则,基本操作有:初始化栈,判断栈空,入栈出栈,读取栈顶元素,代码实现如下

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
/**
* 单个节点
*
* @author Lison-Liou
*
*/
public class Node {
int data = 0;
Node next;

public Node() {
}

public Node(int data) {
this.data = data;
}

public Node(int data, Node next) {
this.data = data;
this.next = next;
}
}
/**
* 后进先出 LIFO LAST IN FIRST OUT
*
* @author Lison-Liou
*
*/
public class MyStack {

Node top;
int size;

public void initStack() {
top = null;
}

public boolean isEmpty() {
return size == 0;
}

public void push(int x) {
top = new Node(x, top);
size++;
}

public int pop() {

Node t = top;
top = top.next;
size--;
return t.data;
}

public int top() {
return top.data;
}
}

测试代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
MyStack stack = new MyStack();
stack.initStack();

System.out.println("入栈操作--------------------------");
for (int i = 0; i < 6; i++) {
int d = random.nextInt(10);
System.out.print(d + "\t");

stack.push(d);
}

System.out.println("\r\n出栈操作--------------------------");
while (!stack.isEmpty())
System.err.print(stack.pop() + "\t");

输出结果