1.链表表示:
首先创建一个类,表示每一个节点
class StackList{ public StackList setHeader(Node header) { this.header = header; return this; } Node header;//栈顶元素 int elementCount;//栈中元素个数 int size;//栈的大小 //通过构造器先设置一个空的栈 public StackList(Node header, int elementCount, int size) { this.header = null; this.elementCount = 0; this.size = 0; } //通过构造器自定义栈的大小 public StackList(int size) { this.header = null; this.elementCount = 0; this.size = size; } //判断栈是否为空 public boolean isEmpty(){ if(elementCount==0){ System.out.println("栈为空"); return true; } return false; } //判断栈是否满 public boolean isFull(){ if(elementCount==size){ System.out.println("栈已满"); return true; } return false; } //入栈 public void push(Object value){ //先判断是否已满 if(this.isFull()){ throw new RuntimeException(); } //重新创建一个栈顶,保存新的数据 header=new Node(value,header); //同时,元素的个数也增加 elementCount++; } //出栈 public void pop(){ //判断是否为空 if(isEmpty()){ throw new RuntimeException(); } Object object=null; while (elementCount>0) { //先取出栈顶的元素 System.out.println( header.getElement()); //将栈顶下移 header = header.next; //栈中元素减少 elementCount--; } } //返回栈顶元素 public Object peak(){ //先判断是否为空 if(isFull()){ throw new RuntimeException(); } return header.getElement(); } }
测试:
2.用数组模拟:
在上面的链表中,需要定义一个栈的大小,因为单向链表没有固定的长度。但是数组可以初始化数组大小的,用于表示栈的大小。
代码如下:
//定义一个类,表示栈结构 class ArrayStack { private int maxSize;//栈的大小 private int[] stack;//数组模拟栈,数据就放在该数组中 private int top = -1;//没有数据时,栈顶初始化为-1 public ArrayStack(int maxSize) { this.maxSize=maxSize; stack=new int[this.maxSize]; } //栈满 public boolean isFull() { return top==maxSize-1; } //栈空 public boolean isEmpty(){ return top==-1; } //入栈——push public void push(int value) { //先判断栈是否满 if(isFull()){ System.out.println("栈已满"); return; }else { top++; stack[top]=value; } } //出栈,将栈顶的数据返回 public int pop(){ //先判断是否为空 if(isEmpty()){ throw new RuntimeException("栈空,没有数据"); } else{ int value=stack[top]; top--; return value; } } //遍历栈,显示栈,从栈顶开始显示数据 public void list(){ //先判断是否为空 if(isEmpty()){ throw new RuntimeException("栈空,没有数据"); } for(int i=top;i>=0;i--){ System.out.printf("stack[%d]=%d\n",i,stack[i]); } } }
下面是测试代码: