1. 程式人生 > >java 實現鏈棧存儲

java 實現鏈棧存儲

out 鏈棧 ext pan args top ram else 代碼

package com.learn.algorithm.linkStack;
/**
 * 鏈棧實現
 * @author Jiekun.Cui
 * @param <T>
 */
public class LinkStack<T> {

    private LinkStack<T>.Node<T> top = new Node<T>();
    private int size=0;
    
    /**
     * 進棧
     * @param t
     * @return  ;
     */
    public boolean
push(T t){ if ( isEmpty() ) { top.next = new Node<T>(t); } else { Node<T> newNode = new Node<T>(t, top.next); top.next = newNode; } size ++ ; return true; } /** * 出棧 *
@param t * @return */ public T pop(){ if ( isEmpty() ) { return null; } else { LinkStack<T>.Node<T> 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 <T> */ class Node<T>{ private T t = null; private Node<T> next = null; public Node(){ } public Node(T t){ this.t = t; } public Node(T t,Node<T> next){ this.t = t; this.next =next; } public T getT() { return t; } public void setT(T t) { this.t = t; } public Node<T> getNext() { return next; } public void setNext(Node<T> next) { this.next = next; } } }

package com.learn.algorithm.linkStack;

/**
 * 鏈棧測試
 * @author Jiekun.Cui
 */
public class Demo {
    
    public static void main(String[] args) {
        LinkStack<Integer> 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 實現鏈棧存儲