简单数据结构实现——堆栈

堆栈 (Stack),最基本的数据结构之一,先进后出的FILO典型结构,主要操作有push(),pop(),top()方法,分别为压栈,出栈,返回栈顶元素。

在下面给出的代码实现中,增加了一些辅助的操作,包括size(), trim(), enlarge(), isEmpty(), toString()方法。

并且因为还没有系统的学习泛型,因此在这里给出的是基于int型的简单实现。运用泛型的通用实现将在以后补完。

Java代码实现:

public class Stack{
	private final double enlargeRatio=0.75;
	private final int DEFAULT_CAPACITY=10;
	private int idxOfTop=0;//Point to next usable position.
	private int capacity;
	private int[] stack;
	
	
	public Stack(){
		stack=new int[DEFAULT_CAPACITY];
		capacity=DEFAULT_CAPACITY;
		
	}

	public Stack(int capacity){
		stack=new int[capacity];
		this.capacity=capacity;
	}
	
/*	
	//Not sure if this constructor is correct!
	public Stack(Collection<? extends AnyType> c){
		capacity=c.length*2;
		stack=new AnyType[capacity];
		
		for(int i=0;i<c.length;i++){
			stack[i]=c[i];
		}
		
		idxOfTop=c.length;
	}
*/
	
	public void push(int element){
		if(idxOfTop+1>=enlargeRatio*stack.length)
			enlarge();
			
		stack[idxOfTop]=element;
		idxOfTop++;		
	}
	
	public void pop(){
		if(!isEmpty())
			idxOfTop--;
		else System.out.println("Stack is empty, can't pop!");
	}
	
	public int top(){
		if(!isEmpty())
			return stack[idxOfTop-1];
		else{
			System.out.println("Stack is empty, no top element!");
			return Integer.MIN_VALUE;
		}
	}
	
	public void trim(){
		capacity=size();
		int[] newStack=new int[capacity];
		
		for(int i=0;i<size();i++){
			newStack[i]=stack[i];
		}
		
		stack=newStack;
	}
	
	public int size(){
		return idxOfTop;
	}
	
	public boolean isEmpty(){
		if(idxOfTop==0) return true;
		else return false;
	}
	
	public String toString(){
		String str="";
		if(isEmpty()) 
			return "This is an empty stack";
		else{
			str+="[";
			for(int i=0;i<size();i++){
				str=str+" "+stack[i];
			}
			str+=" ]";
		}
		
		return str;
	}
	
	//This method will doubly enlarge the stack.
	private void enlarge(){
		capacity*=2;
		int[] newStack=new int[capacity];
		
		for(int i=0;i<size();i++){
			newStack[i]=stack[i];
		}
		
		stack=newStack;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值