Java8实现任意参数的链栈

网友投稿 366 2023-03-19

java8实现任意参数的链栈

Java8实现任意参数的链栈

本文实例为大家分享了java8实现任意参数的链栈,供大家参考,具体内容如下

1、实现功能

1)push():入栈;

2)pop():出栈;

3)getSize():获取栈大小;

4)dihttp://splay():展示栈。

以一下测试进行特别说明:

/**

* The main function.

*/

public static void main(String[] args) {

MyLinkedStack test = new MyLinkedStack<>();

test.push('2');

test.push('+');

test.push('http://-');

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 {

/**

* Only used to store the head node.

*/

private SingleNode 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 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[");

WiuIUCSingleNode 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 test = new MyLinkedStack<>();

test.push('2');

test.push('+');

test.push('-');

test.pop();

test.push('(');

test.display();

}

}//Of class MyLinkedStack

class SingleNode {

/**

* The value.

*/

AnyType val;

/**

* The next node.

*/

SingleNode next;

/**

* The first constructor.

* @param

* paraVal: The given value.

*/

SingleNode (AnyType paraVal) {

val = paraVal;

}//The first constructor

}//Of class SingleNode

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:微信小程序插件开发(小程序开发助手插件)
下一篇:直播软件开发app(夜猫直播视频下载)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~