下面小编就为大家带来一篇java 实现链栈存储的方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
如下所示:
package com.learn.algorithm.linkStack; /** * 链栈实现 * @author Jiekun.Cui * @param */ public class LinkStack { private LinkStack.Node top = new Node(); private int size=0; /** * 进栈<b style="color:transparent">来源gao@!dai!ma.com搞$$代^@码网</b> * @param t * @return ; */ public boolean push(T t){ if ( isEmpty() ) { top.next = new Node(t); } else { Node newNode = new Node(t, top.next); top.next = newNode; } size ++ ; return true; } /** * 出栈 * @param t * @return */ public T pop(){ if ( isEmpty() ) { return null; } else { LinkStack.Node 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 */ class Node{ private T t = null; private Node next = null; public Node(){ } public Node(T t){ this.t = t; } public Node(T t,Node next){ this.t = t; this.next =next; } public T getT() { return t; } public void setT(T t) { this.t = t; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } } }
package com.learn.algorithm.linkStack; /** * 链栈测试 * @author Jiekun.Cui */ public class Demo { public static void main(String[] args) { LinkStack 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 实现链栈存储的方法的详细内容,更多请关注gaodaima搞代码网其它相关文章!