簡單數據結構實現——堆棧

堆棧 (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;
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章