栈
数组栈
初始化
private int top=-1;//top表示栈顶 -1
// private int bottom=-1;
private int[] stack;//数组模拟栈,数据放在数组中
private int maxsize;
public ArrayStack(int maxsize) {
this.maxsize = maxsize;
stack = new int[maxsize];
}
1.栈满
// 栈满
public boolean isFull() {
return top == maxsize - 1;
}
2.栈空
// 栈空
public boolean isEmpty() {
return top == -1;
}
3.入栈
// 入栈
public void push(int data) {
if (isFull()){
throw new RuntimeException("栈满");
}
stack[++top] = data;
}
4.出栈
// 出栈
public int pop() {
if (isEmpty())
throw new RuntimeException("栈空");
return stack[top--];
}
5.栈顶
// 栈顶数据
public int peek(){
if (isEmpty())
throw new RuntimeException("栈空");
return stack[top];
}
6.遍历
// 遍历
public void printStack(){
if (isEmpty())
throw new RuntimeException("栈空");
// 栈顶出,所以从top开始遍历
for (int i = top; i >=0 ; --i) {
System.out.printf("stack[%d]=%d\n",i,stack[i]);
}
}
7.测试
public class ArrayStackDemo {
public static void main(String[] args) {
ArrayStack arrayStack = new ArrayStack(3);
String key="";
boolean loop=true;
Scanner scanner = new Scanner(System.in);
while (loop){
System.out.println("show");
System.out.println("exit");
System.out.println("push");
System.out.println("peek");
System.out.println("pop");
System.out.print("请输入你的选择:");
key=scanner.next();
switch (key){
case "show":
try {
arrayStack.printStack();
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case "push":
try {
System.out.print("请输入你要push的数:");
int value=scanner.nextInt();
arrayStack.push(value);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case "peek":
int peek = arrayStack.peek();
System.out.println("栈顶元素是:"+peek);
break;
case "pop":
try {
int res = arrayStack.pop();
System.out.println("出栈的数是:"+res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case "exit":
scanner.close();
loop=false;
break;
default:
System.out.println("您的输入有误,请输入以下选项:");
}
}
System.out.println("程序退出~~~~");
}
}
链栈
在LinkedListStack类中定义一个Node成员内部类
1.Node类
private Node top;
private class Node {
private int data;
private Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
2.入栈
// 入栈
public void push(int data) {
Node newNode = new Node(data);
if (top == null) {
top = newNode;
} else {
newNode.next = top;
top = newNode;
}
}
3.出栈
// 出栈
public int pop(){
if (top==null){
throw new RuntimeException("栈空");
}
int data=top.data;
top=top.next;
return data;
}
4.栈顶
// 栈顶元素
public int peek(){
if (top==null)
throw new RuntimeException("栈空");
return top.data;
}
5.栈空
// 栈空
public boolean isEmpty(){
return top==null;
}
6.遍历
// 遍历
public void printStack(){
// top指针不能动,需要一个current的辅助指针
Node current=top;
if (top==null)
throw new RuntimeException("栈空");
while (current!=null){
System.out.print(current.data+" ");
current=current.next;
}
System.out.println();
}