栈
1.定义:
栈(stack)是一种先进后出(FILO)的数据结构,只能从一端进行插入和删除的特殊线性表;
压栈:数据进入栈;
弹栈:数据出栈;
2 .实现栈的思路分析
1)使用数组模拟栈;
2)使用top模拟栈顶,初始化为-1;
3)入栈时,top++; stack[top] = data;
- 出栈时,int temp = stack[top]; top--; 返回temp;
package com.sratct.stack;
public class ArrayStack {
public static void main(String[] args) {
Stack stack = new Stack(5);
stack.push(1);
stack.push(3);
stack.push(1);
stack.push(3);
stack.push(1);
stack.getList();
System.out.println(stack.pop());
}
}
class Stack {
private int top;
private int[] stackArr;
private int maxSize;
public Stack(int maxSize) {
this.maxSize = maxSize;
stackArr = new int[maxSize];
top = -1;
}
// 判断栈是否满
public boolean isFull() {
return top == maxSize-1;
}
// 判断栈是否为null
public boolean isNull() {
return top == -1;
}
// 入栈
public void push(int data) {
if (isFull()) {
System.out.println("栈已满");
return;
}
top++;
stackArr[top] = data;
}
//出栈
public int pop() {
if (isNull()) {
throw new RuntimeException("栈为null");
}
int temp = stackArr[top];
top--;
return temp;
}
// 遍历栈
public void getList() {
if (isNull()) {
System.out.println("栈为null");
return;
}
for (int i = top; i>=0;i--) {
System.out.println(stackArr[i]);
}
}
}