如题
由数组构成的顺序栈:
public class Array_Stack { int[] a=new int[10]; int p=-1; public boolean isEmpty() { boolean b=false; if(p==-1) { b=true; } return b; } public boolean isFull() { boolean b=false; if(p==9) { b=true; } return b; } public void push(int x) { if(isFull()) { System.out.println("Statck is full!"); } else { p++; a[p]=x; } } public int pop() { if(isEmpty()) { System.out.println("Statck is empty!"); return -1; } else { return a[p--]; } } }
由链表构成的链式栈:
public class Linked_Stack { int v; Linked_Stack next; public Linked_Stack() { } public Linked_Stack(int x) { v=x; } public boolean isEmpty() { return next==null; } public void push(int x) { Linked_Stack p; p=this.next; next=new Linked_Stack(x); next.next=p; } public int pop() { int x; if(!isEmpty()) { x=next.v; next=next.next; } else { x=-1; System.out.println("Linked_Stack is empty!"); } return x; } }
调用:
public class c1 { public static void main(String[] args) { //顺序栈 Array_Stack myas = new Array_Stack(); int t; for (int i = 1; i <= 15; i++) { myas.push(i); } for (int i = 1; i <= 15; i++) { t = myas.pop(); if (t != -1) { System.out.print(t + "\t"); } } //链式栈 Linked_Stack myls=new Linked_Stack(); for (int i = 1; i <= 12; i++) { myls.push(i); } for (int i = 1; i <= 15; i++) { t = myls.pop(); if (t != -1) { System.out.print(t + "\t"); } } } }
执行结果:
Statck is full! Statck is full! Statck is full! Statck is full! Statck is full! 10 9 8 7 6 5 4 3 2 1 Statck is empty! Statck is empty! Statck is empty! Statck is empty! Statck is empty! 12 11 10 9 8 7 6 5 4 3 2 1 Linked_Stack is empty! Linked_Stack is empty! Linked_Stack is empty!
请注意:顺序栈中对栈顶的描述和书上略有不同。编程看思想,没有一定之规。
Java自带的Stack简单用法:
public static void main(String[] args) { // TODO Auto-generated method stub int t; Stack<Integer> myls = new Stack<Integer>(); for (int i = 1; i <= 12; i++) { myls.push(i); } System.out.println(myls.peek()); System.out.println(myls.size()); for (int i = 1; i <= 15; i++) { if (!myls.empty()) { t = myls.pop(); System.out.print(t + "\t"); } else { System.out.println("Stack is empty."); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现