java 实现链栈存储的方法
更新时间:2017年08月14日 07:45:15 投稿:jingxian
下面小编就为大家带来一篇java 实现链栈存储的方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
如下所示:
package com.learn.algorithm.linkStack; /** * 链栈实现 * @author Jiekun.Cui * @param <T> */ public class LinkStack<T> { private LinkStack<T>.Node<T> top = new Node<T>(); private int size=0; /** * 进栈 * @param t * @return ; */ public boolean push(T t){ if ( isEmpty() ) { top.next = new Node<T>(t); } else { Node<T> newNode = new Node<T>(t, top.next); top.next = newNode; } size ++ ; return true; } /** * 出栈 * @param t * @return */ public T pop(){ if ( isEmpty() ) { return null; } else { LinkStack<T>.Node<T> node = top.next; top.next = node.next; size --; return node.getT(); } } /** * 获取栈顶元素 * @return */ public T getTop(){ if ( isEmpty() ) { return null; } else { return top.next.getT(); } } /** * 判断栈是不是为空 * @return */ public boolean isEmpty(){ return size() == 0; } /** * 返回栈的大小 * @return */ public int size(){ return size; } /** * @author 链栈的节点类 * @param <T> */ class Node<T>{ private T t = null; private Node<T> next = null; public Node(){ } public Node(T t){ this.t = t; } public Node(T t,Node<T> next){ this.t = t; this.next =next; } public T getT() { return t; } public void setT(T t) { this.t = t; } public Node<T> getNext() { return next; } public void setNext(Node<T> next) { this.next = next; } } }
package com.learn.algorithm.linkStack; /** * 链栈测试 * @author Jiekun.Cui */ public class Demo { public static void main(String[] args) { LinkStack<Integer> ls = new LinkStack<>(); ls.push(1); ls.push(2); ls.pop(); ls.push(4); ls.push(5); ls.push(6); while ( !ls.isEmpty() ) { System.out.println(ls.pop()); } } }
以上这篇java 实现链栈存储的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
相关文章
SpringBoot thymeleaf实现饼状图与柱形图流程介绍
这篇文章主要介绍了SpringBoot thymeleaf实现饼状图与柱形图流程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧2022-12-12Dubbo无法访问远程Zookeeper已注册服务的问题解决方案
今天小编就为大家分享一篇关于Dubbo无法访问远程Zookeeper已注册服务的问题解决方案,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧2019-03-03基于SpringBoot集成测试远程连接Redis服务的教程详解
这篇文章主要介绍了基于SpringBoot集成测试远程连接的Redis服务的相关知识,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2020-03-03
最新评论