package com.learn.algorithm.linkStack;/** * 链栈实现 * @author Jiekun.Cui * @param*/public class LinkStack { private LinkStack .Node top = new Node (); private int size=0; /** * 进栈 * @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) { LinkStackls = 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()); } }}
以上代码。