栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

栈的链式存储实现,采用Java语言

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

栈的链式存储实现,采用Java语言

从逻辑结构上来说,栈是只允许在一端进行操作的线性结构;

从存储结构上来说,栈的实现既可以采用顺序存储方式,也可以采用链式存储方式;

以下是栈的链式存储方式实现:


public class Stack {
	
	public static void main(String[] args) {
		Stack stack = new Stack();
		stack.push(-2);
		stack.push(0);
		stack.push(-3);
		System.out.print(stack.getMin());
		stack.pop();
		System.out.print(stack.peek());
		System.out.print(stack.getMin());
	}

	// 指向栈顶的指针
	public Node top;
	public Integer total;
	
	// 结点类
	public class Node {
		public Integer val;
		public Node next;
	}
	
	
	public Stack() {
		this.top = null;
		this.total = 0;
	}
	
	
	public boolean isEmpty() {
		return this.top==null;
	}
	
	
	public void push(Integer val) {
		Node node = new Node();
		node.val = val;
		// 插入头位置
		node.next = this.top;// 当前栈顶结点成为新节点的下一位
		this.top = node;// 更新栈顶结点
		this.total++;
	}
	
	
	public void pop() {
		if(isEmpty()) return;
		Node neNode = this.top;
		this.top = this.top.next;
		this.total--;
	}
	
	
	public Integer peek() {
		if(isEmpty())return null;
		return this.top.val;
	}
	
	
	public Integer getMin() {
		if(isEmpty()) return null;
		Node node = this.top;
		int minVal = node.val;
		while(node!=null) {
			minVal=minVal>node.val?node.val:minVal;
			node=node.next;
		}
		return minVal;
	}
}














转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/999294.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号