栈(线性栈和链栈)

1.线性栈

class LinearStack{
	public int[] array;
	public int size;
	public LinearStack(){
		this(10);
	}
	public LinearStack(int capias){
		array=new int[capias];
		size=0;
	}
	public void push(int e){
		if(size==array.length){
			resize(array.length*2);
		}
		array[size]=e;
		size++;
	}
	public int pop(){
		if(size==0){
			System.out.println("栈为空!");
			return -1;
		}
		int e=array[size-1];
		size--;
		if(size==array.length/4&&array.length>10){
			resize(array.length/2);
		}
		return e;
	}
	public int peek(){
		return array[size-1];
	}
	public int size(){
		return size;
	}
	public void clear(){
		array=new int[10];
		size=0;
	}
	public void print(){
		if(size==0){
			System.out.println("bottom[]top "+size+"/"+array.length);
		}else {
			String s="bottom[";
			for(int i=0;i<size;i++){
				if(i==size-1){
					s+=array[i]+"]top "+size+"/"+array.length;
				}else {
					s+=array[i]+",";
				}
			}
			System.out.println(s);
		}
	}
	public void resize(int capias){
		int[] newArray=new int[capias];
		for(int i=0;i<Math.min(array.length,newArray.length);i++){
			newArray[i]=array[i];
		}
		array=newArray;
	}
}

2.链栈

class ChainStack{
	private int size;
	Node head;
	public ChainStack(){
		this.size=0;
		this.head=new Node();
	}
	public ChainStack(int[] array){
		this();
		for(int i=0;i<array.length;i++){
			push(array[i]);
		}
	}
	public void push(int e){
		head.next=new Node(e,head.next);
		size++;
	}
	public int pop(){
		if(size==0&&head.next==null){
			System.out.println("当前栈为空!");
			return -1;
		}else{
			Node p;
			p=head.next;
			int e=p.e;
			head.next=p.next;
			p=null;
			size--;
			return e;
		}
	}
	public int peek(){
		return head.next.e;
	}
	public int size(){
		return size;
	}
	public void clear(){
		head=null;
		size=0;
	}
	public void print(){
		if(size==0){
			System.out.println("top[]bottom "+size);
		}else{
			String s="top[";
			Node p=head.next;
			while(true){
				if(p.next==null){
					s+=p.e+"]bottom "+size;
					break;
				}else{
					s+=p.e+",";
					p=p.next;
				}
			}
			System.out.println(s);
		}
	}
	private class Node{
		int e;
		Node next;
		public Node(){
			this.e=0;
			this.next=null;
		}
		public Node(int e,Node next){
			this.e=e;
			this.next=next;
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值