本文实例为大家分享了Java8实现任意参数的链栈,供大家参考,具体内容如下
1、实现功能
1)push():入栈;
2)pop():出栈;
3)getSize():获取栈大小;
4)display():展示栈。
以一下测试进行特别说明:
public static void main(String[] args) {
MylinkedStack test = new MylinkedStack<>();
test.push('2');
test.push('+');
test.push('-');
test.pop();
test.push('(');
test.display();
}
输出如下,即输出顺序为栈顶、栈顶下一个…
The linked stack is:
[(, +, 2]
2、代码
package DataStructure;
public class MylinkedStack {
private SingleNode head = new SingleNode(new Object());
private int size = 0;
public void push(AnyType paraVal) {
SingleNode tempNode = new SingleNode<>(paraVal);
tempNode.next = head.next;
head.next = tempNode;
size++;
}//Of push
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
public int getSize() {
return size;
}//Of getSize
public void display() {
if (size == 0) {
throw new RuntimeException("The stack is empty.");
}//Of if
System.out.print("The linked stack is:n[");
SingleNode 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
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 {
AnyType val;
SingleNode next;
SingleNode (AnyType paraVal) {
val = paraVal;
}//The first constructor
}//Of class SingleNode
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



