import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Created by ZYQ on 2016/7/26.
* 实现LIFO(先进后出)的下压栈
*/
public class Stack<String> {
private Node first; // 栈顶
private int N; // 元素数量
// 定义接点的嵌套类
private class Node{
String string;
Node next;
}
// 判断链表是否为空
public boolean isEmpty() {
return first == null;
}
// 统计链表结点数
public int size() {
return N;
}
// 把元素添加在表头
public void push(String s) {
Node oldfirst = first;
first = new Node();
first.string = s;
first.next = oldfirst;
N++;
}
// 将元素从表头删除
public String pop() {
String s = first.string;
first = first.next;
N--;
return s;
}
// 测试用例
public static void main(java.lang.String[] args ) throws IOException{
Stack<java.lang.String> stack = new Stack<java.lang.String>();
// 创建输入流对象,读取一行数据,并以空格为分隔转化为String数组
System.out.println("Enter the statement:");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
java.lang.String intput = reader.readLine();
java.lang.String[] item = intput.split(" ");
for (java.lang.String s : item) {
// 输入"-"代表出栈
if (!s.equals("-")) {
stack.push(s);
} else if (!stack.isEmpty()) {
System.out.println(stack.first.string + " left on stack");
stack.pop();
}
}
// 遍历链表输入下压堆栈的值
System.out.println("The Stack:");
int number = stack.size();
while (number != 0) {
System.out.print(stack.first.string + " ");
stack.first = stack.first.next;
number--;
}
}
}
下压堆栈的链表实现(LIFO)
最新推荐文章于 2023-07-09 08:24:21 发布