Java8實現任意參數的鏈棧
更新時間:2020年10月27日 17:12:50 作者:因吉
這篇文章主要為大家詳細介紹了Java8實現任意參數的鏈棧,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了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
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
相關文章
mybatis-plus報錯net.sf.jsqlparser.statement.select.SelectBody的
本文主要介紹了mybatis-plus報錯net.sf.jsqlparser.statement.select.SelectBody的問題解決,具有一定的參考價值,感興趣的可以了解一下2024-08-08
淺談SpringBoot Bean加載優(yōu)先級的問題
這篇文章主要介紹了淺談SpringBoot Bean加載優(yōu)先級的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11

