Java用数组实现《数据结构》中栈的出入 。

接口:

public interface MyStack {
	//获取栈中的元素个数
		int getSize();
	//1.判断栈空
		public boolean isEmpty();
	//2.判断栈满
		public boolean isFull();
	//3.入栈
		void push(Object obj);
	//4.出栈
		void out();
		
	//5.打印
		void printStack();


}

方法的实现:


public class Stack implements MyStack{
	    //定义索引头和索引尾
		private int head,end;
		//定义数组
		private Object[] queque;
		//定义最大长度
		private int maxSize;
		//当前队列内的元素个数
		private int size;
		public Stack(int maxSize) {
			this.head=0;
			this.end=0;
			this.maxSize=maxSize;
			this.size=0;
			this.queque= new Object[maxSize];
		}

	@Override
	public int getSize() {
		
		return this.size;
	}

	@Override
	public boolean isEmpty() {
		if(size==0) {
			System.out.println("栈空");
		}
		return false;
	}

	@Override
	public boolean isFull() {
		return this.size==this.maxSize;
	}

	@Override
	public void push(Object obj) {
		if(isFull()) {
			System.out.println("栈已满,不能入栈。");
			return;
		}
		queque[end]=obj;      
		//索引尾向后移动一个位置,利用对最大长度求余来达到循环 
		end=(end+1)%maxSize; 
		this.size++;
		System.out.println("添加:“"+obj+"”添加成功");
	}

	@Override
	public void out() {
		if(isEmpty()) {
			System.out.println("栈已空,不能出栈。");
			return;
		}
		//出队后头索引头会向后移动,利用队最大长度求余来达到循环
		head=(head+1)%maxSize;
		this.size--;
		System.out.println("出栈成功");
	}

	@Override
	public void printStack() {
		if(isEmpty()) {
			System.out.println("栈以空");
		}
		else {
			System.out.println();
			if(isFull()) {
				for (int i = 0; i < maxSize; i++) {
					System.out.print(queque[i]+"\t");
				}
			}
			else {
				//有出队后再添加到出队空出位置的情况
				if(end<size && head>0) {
					for (int i = 0; i < end; i++) {
						System.out.print(queque[i]+"\t");
					}
					for (int i = head; i < maxSize; i++) {
						System.out.print(queque[i]+"\t");
					}
				}
				//队列不满
				else {
					for (int i = head; i < end; i++) {
						System.out.print(queque[i]+"\t");
					}
				}
			}
			System.out.println();
		}
		
	}


}

测试类:

public class TestStack {
	public static void main(String[] args) {
		Stack s=new Stack(5);
		s.printStack();
		s.push("我");
		s.push("你");
		s.push("他");
		s.printStack();
		s.out();
		s.printStack();
		s.push("我");
		s.printStack();
	}
}

上一篇:埃氏筛法(c语言)


下一篇:Python模拟队列