这篇文章运用简单易懂的例子给大家介绍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实现一个任意参数的链栈就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。