4、链栈的实现(java代码)
2024-09-01 08:44:54
1、链节点
public class Node<T> {
public T data;
public Node next;
}
2、实现代码
public class Stack<T> {
private static Node bottom; //栈底指针
private static Node top; //栈顶指针
private static Integer size; //栈当前大小 /**
* 初始化
*/
public void initStack() {
bottom = top = new Node();
top.next = bottom;
size = 0;
} /**
* 是否空
*
* @return
*/
public static boolean isEmpty() {
if (top.next == bottom) {
return true;
}
return false;
} /**
* 入栈
*
* @param element
*/
public void pushStack(T element) {
Node temp = new Node();
temp.data = element;
if (top.next == bottom)//第一次入栈操作
{
temp.next = bottom;
top.next = temp;
} else {
temp.next = top.next;
top.next = temp;
}
size++;
} /**
* 出栈
*/
public void popStack() { if (isEmpty()) {
System.out.println("栈中没有元素!");
} else {
System.out.println("出栈操作:" + top.next.data + " ");
top.next = top.next.next;
}
size--;
} /**
* 元素个数
*
* @return :个数值
*/
public int sizeStack() {
return size;
} /**
* 查看顶部值
*/
public static void getTop() {
System.out.println("顶部值:" + top.next.data);
} /**
*
* 打印放入的元素
*/
public static void printStack() {
Node temp = top;
if (isEmpty()) {
System.out.println("栈中没有元素!");
} else {
for (int i = 0; i < size; i++) {
System.out.print(temp.next.data + " ");
temp = temp.next;
}
}
System.out.println(); } public static void main(String[] args) {
Stack<Integer> integerStack = new Stack<>();
integerStack.initStack();
integerStack.pushStack(1);
printStack();
integerStack.pushStack(2);
printStack();
integerStack.pushStack(3);
printStack();
integerStack.pushStack(4);
printStack(); integerStack.popStack();
printStack();
integerStack.pushStack(4);
printStack();
integerStack.popStack();
printStack(); System.out.println("大小:" + integerStack.sizeStack()); getTop();
}
3、结果展示
1
2 1
3 2 1
4 3 2 1
出栈操作:4
3 2 1
4 3 2 1
出栈操作:4
3 2 1
大小:3
顶部值:3
最新文章
- 摘要: Linux下which、whereis、locate、find命令的区别
- react经典进阶demo
- 杭电OJ——1198 Farm Irrigation (并查集)
- 读propert文件
- ajax请求或者页面需要缓存,代码如下
- .NET中利用反射来实现自动映射两个对象中的数据成员
- 用Java写的简单五子棋游戏(原创五子连珠算法)
- python读取excel时,数字自动转化为float
- C#版(击败97.76%的提交) - Leetcode 557. 反转字符串中的单词 III - 题解
- 痞子衡嵌入式:串口调试工具Jays-PyCOM诞生记(3)- 串口功能实现(pySerial)
- poi 导入Excle
- C#:如何使方法过时,如何否决方法
- Win7 下安装ubuntu14.04双系统
- java流程控制语句总结
- Parco_Love_gcd
- nisght heap increase
- python 全栈开发,Day111(客户管理之 编辑权限(二),Django表单集合Formset,ORM之limit_choices_to,构造家族结构)
- # 2017-2018-2 20155231《网络对抗技术》实验九: Web安全基础实践
- CORS support for ASP.NET Web API (转载)
- 日期插件rolldate.js的使用