用链表实现栈
作者:互联网
class MyStack {
private final static MyStack head = new MyStack();
int val;
MyStack next;
public MyStack() {
}
private MyStack(int val) {
this.val = val;
}
//入栈
public boolean push(int val) {
if (next == null) {
next = new MyStack(val);
return true;
}
MyStack dummy = next;
while (dummy.next != null) {
dummy = dummy.next;
}
dummy.next = new MyStack(val);
return true;
}
//出栈
public boolean outStack() {
MyStack myStack = next;
if (myStack == null) {
System.out.println("栈空");
return false;
}
while (myStack.next != null && myStack.next.next != null) {
myStack = myStack.next;
}
myStack.next = null;
return true;
}
//打印
public void println() {
MyStack dummy = next;
if (dummy == null) {
System.out.println("栈空");
}
while (dummy != null) {
System.out.println(dummy.val);
dummy = dummy.next;
}
}
}
标签:dummy,val,实现,next,链表,myStack,MyStack,null 来源: https://blog.csdn.net/weixin_57929476/article/details/122526937