java栈实现
java栈实现
数组实现
Stack类
class Stack {
private int maxSize;
private int[] stack;
private int top = -1;
public Stack(int maxSize) {
this.maxSize = maxSize;
stack = new int[maxSize];
}
public void show() {
if (isEmpty()) {
System.out.println("栈空的");
return;
}
for (int i = top; i >= 0; --i) {
System.out.println("stack[" + i + "] ==> " + stack[i]);
}
}
public void push(int value) {
if (isFull()) {
System.out.println("栈满了");
return;
}
// 插入数据
stack[++top] = value;
}
public Integer pop() {
if (isEmpty()) {
System.out.println("栈是空的");
return null;
}
// pop
return stack[top--];
}
public boolean isFull() {
return (top == maxSize - 1);
}
public boolean isEmpty() {
return (top == -1);
}
}
测试类
public class StackDemo {
public static void main(String[] args) {
Stack stack = new Stack(3);
String key = "";
boolean loop = true;
Scanner scanner = new Scanner(System.in);
Scanner numInput = new Scanner(System.in);
while (loop) {
System.out.println("show:显示栈");
System.out.println("push:压元素入栈");
System.out.println("pop:弹元素出栈");
System.out.println("exit:退出");
key = scanner.nextLine();
switch (key) {
case "show":
stack.show();
break;
case "push":
System.out.println("输入一个要压入栈的数");
int num = numInput.nextInt();
stack.push(num);
break;
case "pop":
System.out.println(stack.pop());
break;
case "exit":
scanner.close();
numInput.close();
System.exit(0);
break;
default:
System.out.println("输入不合法");
break;
}
}
}
}
链表实现
节点类
class Node {
public int id;
public Node pre;
public Node next;
public Node(int id) {
this.id = id;
}
@Override
public String toString() {
return "Node{" +
"id=" + id +
", next=" + next +
'}';
}
}
Stack类
class LinkedListStack {
private Node head = new Node(0);
private Node top = new Node(0);
public void show() {
if (isEmpty()) {
System.out.println("栈空");
return;
}
Node tem = top.next;
while (true) {
if (tem == head) {
break;
}
System.out.println(tem);
tem = tem.pre;
}
}
public Node pop() {
if (isEmpty()) {
System.out.println("栈空");
return null;
}
Node tem = top.next;
top.next = null;
top = top.pre;
return tem;
}
public void push(Node node) {
Node tem = head;
while (true) {
if (tem.next == null) {
break;
}
// 移动tem
tem = tem.next;
}
// push并移动top
tem.next = node;
node.pre = tem;
top = tem;
}
private boolean isEmpty() {
return (head.next == null);
}
}
测试类
public class StackDemo {
public static void main(String[] args) {
LinkedListStack linkedListStack = new LinkedListStack();
linkedListStack.push(new Node(0));
linkedListStack.push(new Node(1));
linkedListStack.push(new Node(2));
linkedListStack.pop();
linkedListStack.show();
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构