大家知道,栈的实现可以是链表或数组或其他多种方式,链表的好处就是不会限制大小而且出栈和入栈速度都很快。下面我们来看代码:
public class ListNode{
Object val;
ListNode next = null;
public ListNode(Object val){
this.val = val;
}
}
public interface StackInterf {
//定义压栈操作
public void push(Object o);
//定义出栈操作
public Object pop() throws Exception;
//返回栈顶元素
public Object peek();
//返回栈大小
public int size();
//判断是否为空
public boolean isEmpty();
//tostring
public String toString();
}
public class LinkedStack implements StackInterf{
ListNode top;//指向栈顶
private int size;//定义栈大小
public LinkedStack(){
top=null;
size=0;
}
public void push(Object o){
ListNode node = new ListNode(o);
node.next = top;
top = node;
size++;
}
public Object pop()throws Exception{
if(isEmpty()){
throw new Exception("stack is empty!");
}
Object result = top.val;
top = top.next;
size--;
return result;
}
public Object peek(){
Object result = top.val;
return result;
}
public int size(){
return size;
}
public boolean isEmpty(){
if(size!=0){
return false;
}
return true;
}
}
public class Test{
public static void main(String[] args){
LinkedStack stack = new LinkedStack();
//把1到10依次入栈
for(int i=0;i<10;i++){
stack.push(i);
}
//连续5次出栈操作
for(int i=0;i<5;i++){
try {
stack.pop();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("栈为空吗?: " + stack.isEmpty());
System.out.println("栈的大小为: " + stack.size());
System.out.println("栈顶元素为: " + stack.top.val);
System.out.println("栈顶元素为: " + stack.peek());
}
}