赞
踩
实际需求
栈的介绍
出栈和入栈示意图
package com.datastructures.stack; import java.util.Scanner; public class ArrayStackDemo { public static void main(String[] args) { //测试ArrayStack是否正确 //先创建一个ArrayStack的对象,即一个栈 ArrayStack stack = new ArrayStack(4); 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("show:表示从栈中取出数据(出栈)"); System.out.println("请输出你的选择:"); key = scanner.next(); switch (key) { case "show": stack.list(); break; case "push": System.out.println("请输入一个数:"); int value = scanner.nextInt(); stack.push(value); break; case "pop": try { int res = stack.pop(); System.out.printf("出栈的数据是%d\n",res); } catch (Exception e) { System.out.println(e.getMessage()); } break; case "exit": scanner.close(); loop = false; break; default: break; } } System.out.println("程序退出"); } } //定义一个类ArrayStack 表示栈 class ArrayStack{ private int maxSize; //栈的大小 private int[] stack; //数组,数组模拟栈,数据就放在该数组 private int top = -1; //top表示栈顶,初始化为-1 //构造器 public ArrayStack(int maxSize) { this.maxSize = maxSize; stack = new int[this.maxSize]; //根据传进来的栈大小,创建数组 } //栈满 public boolean isFull() { return top == maxSize - 1; } //栈空 public boolean isEmpty() { return top == -1; } //入栈-push public void push(int value) { //先判断是否栈满 if(isFull()) { System.out.println("栈满"); return; } top++; stack[top] = value; } //出栈-pop,将栈顶的数据返回 public int pop() { //先判断栈是否为空 if(isEmpty()) { //抛出异常 throw new RuntimeException("栈空"); } int value = stack[top]; top--; return value; } //遍历栈 遍历时需要从栈顶开始显示 public void list() { if(isEmpty()) { System.out.println("栈空"); return; } for(int i = top; i >= 0; i--) { System.out.printf("stack[%d]=%d\n",i,stack[i]); } } }
使用数组模拟栈,在删除时,虽然表面上看起来删除成功,其实在数组中,被删除的数据仍然存在;可以使用单链表来模拟栈。
考虑栈是先进后出,让head.next始终指向每次新插入的节点
package com.datastructures.stack;
public class LinkedlistStackDemo {
public static void main(String[] args) {
StackNode stackNode1 = new StackNode(1);
StackNode stackNode2 = new StackNode(2);
StackNode stackNode3 = new StackNode(3);
StackNode stackNode4 = new StackNode(4);
StackNode stackNode5 = new StackNode(5
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。