Heim > Java > javaLernprogramm > Hauptteil

Java-Sonderthema zum Thema Stack

Y2J
Freigeben: 2017-04-24 13:38:00
Original
1104 Leute haben es durchsucht

package java栈;
public class Stack {
	private int maxSize;
	private Object[] data;
	private int top;//栈顶位置
	/**
	 * 初始化栈
	 * @param maxSize
	 */
	public Stack(int maxSize){
		this.maxSize = maxSize;
		data = new Object[maxSize];
		top = -1;
	}
	
	/**
	 * 获取长度
	 * @param args
	 */
	public int getLength(){
		return this.maxSize;
	}
	/**
	 * 返回栈中元素个数
	 * @param args
	 */
    public int getCount(){
    	return top+1;
    }
	/**
	 * 判断栈空
	 * @param args
	 */
	public boolean isEmpty(){
		return top == -1;
	}
	/**
	 * 判断栈满
	 * @param args
	 */
	public boolean isFull(){
		return top+1 == this.maxSize;
	}
	/**
	 * 入栈
	 * @param args
	 * @throws Exception 
	 */
	public boolean push(Object data) throws Exception{
		if(isFull()){
			throw new Exception("栈已满");
			
		}else{
			this.data[++top] = data;
			return true;
		}
	}
	/**
	 * 出栈
	 * @param args
	 * @throws Exception 
	 */
	public Object pop() throws Exception{
		if(isEmpty()){
			throw new Exception("栈已空");
		}else{
			return this.data[top--];
		}
	}
	/**
	 * 返回栈顶元素
	 * @param args
	 */
	public Object peek(){
		return this.data[this.getCount()];
	}
	public static void main(String[] args) throws Exception {
		Stack stk = new Stack(6);
		System.out.println("栈空间大小为:" + stk.getLength());
		System.out.println("入栈1:" + stk.push(1));
		System.out.println("入栈2:" + stk.push(2));
		System.out.println("入栈3:" + stk.push(3));
		System.out.println("入栈4:" + stk.push(4));
		System.out.println("入栈5:" + stk.push(5));
		System.out.println("入栈6:" + stk.push(6));
		//System.out.println("入栈7:" + stk.push(7));
		System.out.println("栈元素个数:" + stk.getCount());
		System.out.println("返回头:" + stk.peek());
		
		System.out.println("出栈:" + stk.pop());
		System.out.println("出栈:" + stk.pop());
		System.out.println("出栈:" + stk.pop());
		
		//System.out.println("出栈:" + stk.pop());//异常抛出
	}
}
Nach dem Login kopieren

Das obige ist der detaillierte Inhalt vonJava-Sonderthema zum Thema Stack. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!