栈的两种实现方法--数组实现与链式实现

栈(stack)是限制插入和删除只能在一个位置上进行的表,该位置是表的末端,叫做栈顶(top)。栈又叫做先进后出(Last In First Out)表。

栈通过push向栈输入,通过poptop从栈中输出,只有栈顶元素可以访问。

栈有两种实现方法,一种是是通过数组实现,一种是链式实现。

数组实现代码如下:

public class ArrayStack<AnyType> {
    
	private AnyType []theArray;  //存储空间基址
	private int topOfStack;  //栈顶
	private static final int space=10;  //数组容量
	
	public ArrayStack(){
		topOfStack=-1;
		increaseSpace(space);
	}
	
	public boolean isEmpty(){          //判断是否为空
		return topOfStack==-1;
	}
	
	public void push(AnyType x){         //压栈
		if(topOfStack>space)
			increaseSpace(space+1);
		topOfStack++;
		theArray[topOfStack]=x;
	}
	
	public AnyType pop() {                 //出栈
		if(topOfStack==-1)
			return null;
        AnyType a=theArray[topOfStack];
        topOfStack--;
        return a;
	}
	
	public void increaseSpace(int space){    //扩容
		AnyType old[]=theArray;
		theArray=(AnyType []) new Object[space];
		for(int i=0;i<topOfStack+1;i++)
			theArray[i]=old[i];
	}
	public static void main(String[] args) {
	    ArrayStack<Integer> as=new ArrayStack<Integer>();
	    as.push(1);
	    as.push(2);
	    as.push(3);
	    as.push(4);
	    System.out.println(as.pop());
	    System.out.println(as.pop());
	    System.out.println(as.pop());
	    System.out.println(as.pop());
	    System.out.println(as.pop());
        
	}

}


通过链式实现的代码如下:

public class SingleLinkedStack<AnyType> {

	private Node<AnyType> top;
	private int theSize;
	
	class Node<AnyType>{        //结点Node类
		 public AnyType data;
		 public Node<AnyType> next;
		 public Node(AnyType d,Node<AnyType> next ){
			 this.data=d;
			 this.next=next;
		 }
		 public Node(AnyType d){
			 this.data=d;
			 this.next=null;
		 }
		 public Node(){
			 this.data=null;
			 this.next=null;
		 }
		
	}
	
	public SingleLinkedStack(){
		top=null;
		theSize=0;
	}
	
	public boolean isEmpty(){
		return theSize==0;
	}
	
	public void push(AnyType x){
		Node<AnyType> newNode=new Node(x);
		newNode.next=top;
		top=newNode;
		theSize++;
	}
	
	public AnyType pop(){
		if(isEmpty())
			return null;
		AnyType a=top.data;
		top=top.next;
		theSize--;
		return a;
	}
	public static void main(String[] args) {
		SingleLinkedStack<String> sls=new SingleLinkedStack<String>();
		sls.push("aaa");
		sls.push("bbb");
		sls.push("ccc");
		sls.push("ddd");
		System.out.println(sls.pop());
		System.out.println(sls.pop());
		System.out.println(sls.pop());
		System.out.println(sls.pop());
		

	}

}


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

光光-Leo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值