Java data structures and algorithms - Stack

线性结构之一:栈
栈是一个先入后出的有序列表
栈的元素不能从列表中间增加和删除,
只能从顶端增删数据,称为栈顶;
底端为固定的一端不进行元素的增删,称为栈底

Analog array stack

栈类:
属性:栈大小/数组模拟栈/栈顶(top = -1)
方法:
判断栈是否满:用栈顶的标记值top == 栈大小 - 1
判断栈是否空:top ==  - 1
入栈
出栈
显示栈所有数据
显示栈顶元素
构造器:初始化数组大小
package stack;

public class MyStackInt {
	private int maxSize;// 栈大小
	private int[] stack;// 数组栈
	private int top = -1;// 栈顶

	public MyStackInt() {
		super();
		// TODO Auto-generated constructor stub
	}

	public MyStackInt(int maxSize) {
		super();
		this.maxSize = maxSize;
		this.stack = new int[maxSize];
	}

	// 判断栈是否满
	public boolean isFull() {
		// return stack.length == maxSize;
		return top == maxSize - 1;
	}

	// 判断栈是否已经空
	public boolean isEmpty() {
		// return stack.length == 0;
		return top == -1;
	}

	// 入栈
	public void push(int i) {
		// 先判断栈是否已满
		if (isFull()) {
			System.out.println("栈已经满了!");
			return;
		}
		top++;
		stack[top] = i;
		System.out.println("添加成功!");
	}

	// 出栈
	public int pop() {
		if (isEmpty()) {
			// System.out.println("栈已经空了");
			// return -1;
			throw new RuntimeException("栈已经空了");
		}
		int temp = stack[top];
		top--;
		System.out.println("取值成功! " + temp);
		return temp;
	}
	//显示栈顶元素不是取出元素
	public int peek() {
		if (isEmpty()) {
			throw new RuntimeException("栈已经空了");
		}
		return stack[top];

	}

	// 遍历栈的元素(不是取值),先进后出
	public void list() {
		if (isEmpty()) {
			System.out.println("栈已经空了");
			return;
		}

		for (int i = top; i >= 0; i--) {
			System.out.println(stack[i]);
		}
	}

}

Test categories:

		MyStackInt stack = new MyStackInt(5);
		stack.push(1);
		stack.push(2);
		stack.push(3);
		stack.push(4);
		System.out.println("栈顶元素" + stack.peek());
		stack.list();
		stack.pop();
		System.out.println("栈顶元素" + stack.peek());
		stack.list();

Published 29 original articles · won praise 0 · Views 349

Guess you like

Origin blog.csdn.net/qq_31241107/article/details/104715458