如下所示:
package com.learn.algorithm.linkStack; public class linkStack{ private linkStack .Node top = new Node (); private int size=0; 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; } public T pop(){ if ( isEmpty() ) { return null; } else { linkStack .Node node = top.next; top.next = node.next; size --; return node.getT(); } } public T getTop(){ if ( isEmpty() ) { return null; } else { return top.next.getT(); } } public boolean isEmpty(){ return size() == 0; } public int size(){ return size; } 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;
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 实现链栈存储的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持考高分网。



