java 实现链栈存储的方法
如下所示:
packagecom.learn.algorithm.linkStack; /** *链栈实现 *@authorJiekun.Cui *@param*/ publicclassLinkStack { privateLinkStack .Node top=newNode (); privateintsize=0; /** *进栈 *@paramt *@return; */ publicbooleanpush(Tt){ if(isEmpty()){ top.next=newNode (t); }else{ Node newNode=newNode (t,top.next); top.next=newNode; } size++; returntrue; } /** *出栈 *@paramt *@return */ publicTpop(){ if(isEmpty()){ returnnull; }else{ LinkStack .Node node=top.next; top.next=node.next; size--; returnnode.getT(); } } /** *获取栈顶元素 *@return */ publicTgetTop(){ if(isEmpty()){ returnnull; }else{ returntop.next.getT(); } } /** *判断栈是不是为空 *@return */ publicbooleanisEmpty(){ returnsize()==0; } /** *返回栈的大小 *@return */ publicintsize(){ returnsize; } /** *@author链栈的节点类 *@param */ classNode { privateTt=null; privateNode next=null; publicNode(){ } publicNode(Tt){ this.t=t; } publicNode(Tt,Node next){ this.t=t; this.next=next; } publicTgetT(){ returnt; } publicvoidsetT(Tt){ this.t=t; } publicNode getNext(){ returnnext; } publicvoidsetNext(Node next){ this.next=next; } } }
packagecom.learn.algorithm.linkStack;
/**
*链栈测试
*@authorJiekun.Cui
*/
publicclassDemo{
publicstaticvoidmain(String[]args){
LinkStackls=newLinkStack<>();
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实现链栈存储的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。