手写一个栈

package com.bl.zyj;

/**
 * @author zhangyajing
 *
 */
public class MyStack {
	
	int arr[];
	int top;

	public MyStack(){
		arr = new int [5];
		top = -1;
	}

	public MyStack(int max){
		arr = new int [max];
		top = -1;
	}

	/**
	 * @param value
	 * 增加数据项
	 */
	public void add(int value){
		arr[++top] = value;
	}

	/**
	 * @return
	 * 先进后出提取数据项
	 */
	public int pop(){
		return arr[top--];
	}
	

	/**
	 * @return
	 * 读取数据项	
	 */
	public int peek(){
		return arr[top];
	}
	
	/**
	 * 栈此刻状态,是否为空或者栈是否满
	 */
	public void isState(){
		if (top == -1) {
			System.out.println("此刻栈为空"); 
		} else if (top == arr.length-1) {
			System.out.println("此刻栈满爆了!!!!!");
		} else {
			System.out.println("删除中或读取中或栈不满");
		}
	}
}
package com.bl.zyj;

public class TestMyStack {
	public static void main(String[] args) {
		MyStack ms = new MyStack();
		
		ms.add(10);
		ms.add(5);
		ms.add(85);
		ms.add(1);
		ms.add(36);
		
		ms.isState();
		
		System.out.println(ms.peek());
	
		System.out.println("---------");
		
		while(ms.top != -1){
			System.out.println(ms.pop());
		}
		ms.isState();
	}
}
运行结果如下:
此刻栈满爆了!!!!!
36
---------
36
1
85
5
10
此刻栈为空


猜你喜欢

转载自blog.csdn.net/zaoanmiao/article/details/80087307