package com.loong.datastructure;
/**
* 链栈
*
* @author Loong
* @param <E>
*
*/
public class LinkedStack {
Node first;
/**
* 获取栈顶元素
*
* @return
*/
public Object getTop() {
if (isStackEmpty()) {
throw new RuntimeException("栈为空");
} else {
return first;
}
}
/**
* 压栈
*
* @param o
*/
public void add(Object o) {
Node n = new Node(o, first);
first = n;
}
/**
* 退栈
*
* @return
*/
public Object pop() {
if (isStackEmpty()) {
throw new RuntimeException("栈为空");
} else {
first = first.next;
return first;
}
}
/**
* 判断栈是否为空
*
* @return
*/
public boolean isStackEmpty() {
return first == null;
}
private static class Node {
Object item;
Node next;
Node(Object element, Node next) {
this.item = element;
this.next = next;
}
}
public static void main(String[] args) {
LinkedStack ls = new LinkedStack();
ls.add("zhong");
ls.add("2");
ls.add("3");
ls.add("4");
Node n = (Node) ls.getTop();
System.out.println(n.item);
ls.pop();
n = (Node) ls.getTop();
System.out.println(n.item);
ls.pop();
n = (Node) ls.getTop();
System.out.println(n.item);
ls.pop();
n = (Node) ls.getTop();
System.out.println(n.item);
ls.pop();
n = (Node) ls.getTop();
System.out.println(n.item);
}
}
链栈
最新推荐文章于 2022-08-17 11:17:33 发布