這篇文章運用簡單易懂的例子給大家介紹Java8實現一個任意參數的鏈棧,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
1、實現功能
1)push():入棧;
2)pop():出棧;
3)getSize():獲取棧大??;
4)display():展示棧。
以一下測試進行特別說明:
/** * The main function. */ public static void main(String[] args) { MyLinkedStack <Character> test = new MyLinkedStack<>(); test.push('2'); test.push('+'); test.push('-'); test.pop(); test.push('('); test.display(); }
輸出如下,即輸出順序為棧頂、棧頂下一個…
The linked stack is:
[(, +, 2]
2、代碼
package DataStructure; /** * @author: Inki * @email: inki.yinji@qq.com * @create: 2020 1026 * @last_modify: 2020 1026 */ public class MyLinkedStack <AnyType> { /** * Only used to store the head node. */ private SingleNode<AnyType> head = new SingleNode(new Object()); /** * The single linked list current size. */ private int size = 0; /** * Push element to the end of the list. * @param: * paraVal: The given value. */ public void push(AnyType paraVal) { SingleNode <AnyType> tempNode = new SingleNode<>(paraVal); tempNode.next = head.next; head.next = tempNode; size++; }//Of push /** * Pop the last element. * @return: * The popped value. */ public AnyType pop(){ if (size == 0) { throw new RuntimeException("The stack is empty."); } AnyType retVal = head.next.val; head.next = head.next.next; size--; return retVal; }//Of pop /** * Get the current size of the single linked list. * @return: * The current size of the single linked list. */ public int getSize() { return size; }//Of getSize /** * Display the single linked list. */ public void display() { if (size == 0) { throw new RuntimeException("The stack is empty."); }//Of if System.out.print("The linked stack is:\n["); SingleNode <AnyType> tempNode = head; int i = 0; while (i++ < size - 1) { tempNode = tempNode.next; System.out.printf("%s, ", tempNode.val); }//Of while System.out.printf("%s]\n", tempNode.next.val); }//Of display /** * The main function. */ public static void main(String[] args) { MyLinkedStack <Character> test = new MyLinkedStack<>(); test.push('2'); test.push('+'); test.push('-'); test.pop(); test.push('('); test.display(); } }//Of class MyLinkedStack class SingleNode <AnyType>{ /** * The value. */ AnyType val; /** * The next node. */ SingleNode<AnyType> next; /** * The first constructor. * @param * paraVal: The given value. */ SingleNode (AnyType paraVal) { val = paraVal; }//The first constructor }//Of class SingleNode
關于Java8實現一個任意參數的鏈棧就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。