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

栈(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());
		

	}

}


 

posted @ 2013-10-13 12:17  IT专业户  阅读(240)  评论(0编辑  收藏  举报