如下所示:
packagecom.learn.algorithm.linkStack; /** * 链栈实现 * @author Jiekun.Cui * @param*/ publicclassLinkStack { privateLinkStack .Node top =newNode (); privateintsize=0; /** * 进栈 * @param t * @return ; */ publicbooleanpush(T t){ if( isEmpty() ) { top.next =newNode (t); }else{ Node newNode =newNode (t, top.next); top.next = newNode; } size ++ ; returntrue; } /** * 出栈 * @param t * @return */ publicT pop(){ if( isEmpty() ) { returnnull; }else{ LinkStack .Node node = top.next; top.next = node.next; size --; returnnode.getT(); } } /** * 获取栈顶元素 * @return */ publicT getTop(){ if( isEmpty() ) { returnnull; }else{ returntop.next.getT(); } } /** * 判断栈是不是为空 * @return */ publicbooleanisEmpty(){ returnsize() ==0; } /** * 返回栈的大小 * @return */ publicintsize(){ returnsize; } /** * @author 链栈的节点类 * @param */ classNode { privateT t =null; privateNode next =null; publicNode(){ } publicNode(T t){ this.t = t; } publicNode(T t,Node next){ this.t = t; this.next =next; } publicT getT() { returnt; } publicvoidsetT(T t) { this.t = t; } publicNode getNext() { returnnext; } publicvoidsetNext(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());
}
}
}