数据结构之顺序栈实现与操作(java实现)

一、栈的定义

            栈:栈是限定仅在表尾进行插入或则删除操作的线性表,对栈来说表尾端我们称之为栈顶,表头端称为栈底。

            数据特点:先进后出


二、顺序栈的定义

          顺序栈:利用顺序存储结构实现的栈,即利用一组地址连续的存储单元依次存放自栈底到栈顶的数据元素

          优点:相比于链栈,顺序栈在实现以及操作上均比链栈要容易许多

          缺点:相比链栈,顺序栈只能在事先进行预申请,所以在存放较大数据量的数据时会存在栈满或则说时栈溢出的情况,在用顺序栈时需提前注意


三、顺序栈的存储与实现

        1、顺序栈存储

        private int[] base=null;
	private int top;
	public int MaxSize;
	
	public MyStack() {
		this(10);
	}

        2、入栈

        public boolean Push(int n) {
		
		if(this.isFull())
			return false;
		
		base[top]=n;
		top++;
		return true;
	}

       3、出栈

        public int Pop() {
		
		int n;
		
		if(this.isEmpty()) {
			System.out.println("栈已空,无法继续操作");
			return -1;
		}
		
		
		top--;
		n=base[top];
		return n;
			
	}


四、整体程序实现

            MyStack.java

    package Stack;

    public class MyStack {

	private int[] base=null;
	private int top;
	public int MaxSize;
	
	public MyStack() {
		this(10);
	}
	
	public MyStack(int n) {
		
		if(n>0) {
			base=new int[n];
			MaxSize=n;
			top=0;
		}		
	}
	
	public boolean isEmpty() {
		
		if(top==0)
			return true;
		else
			return false;
	}
	
	public boolean isFull() {
		if(top==MaxSize)
			return true;
		else
			return false;
	}
	
	public boolean Push(int n) {
		
		if(this.isFull())
			return false;
		
		base[top]=n;
		top++;
		return true;
	}

	public int Pop() {
		
		int n;
		
		if(this.isEmpty()) {
			System.out.println("栈已空,无法继续操作");
			return -1;
		}
		
		
		top--;
		n=base[top];
		return n;
			
	}

	
}

附:介于本人理解与编码能力有限欢迎各位批评指正

      本文皆为作者原创,若要转载请注明出处



猜你喜欢

转载自blog.csdn.net/qq_36441169/article/details/80760372