package stack;
import java.util.Scanner;
public class SingleLinkedListStackTest {
public static void main(String[] args) {
SingleLinkedListStack singleLinkedListStack = new SingleLinkedListStack();
Scanner scanner = new Scanner(System.in);
boolean loop = true;
String key = "";
while(loop == true){
System.out.println("向栈加入数据:" + "push");
System.out.println("显示队栈中数据:" + "show");
System.out.println("获取栈顶数据:" + "pop");
System.out.println("退出:" + "exit");
System.out.println("请输入你的选项:");
key = scanner.next();
switch (key){
case "push":
System.out.println("请输入一个整数");
int value = scanner.nextInt();
singleLinkedListStack.push(value);
break;
case "show":
singleLinkedListStack.show();
break;
case "pop":
try {
System.out.println(singleLinkedListStack.pop());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case "exit":
loop = false;
break;
default:
System.out.println("请输入正确指令");
break;
}
}
System.out.println("程序退出");
}
}
class SingleLinkedListStack{
StackNode first = null;
int top = -1;
public boolean isEmpty(){
return top == -1;
}
public void push(int value){
StackNode stackNode= new StackNode(value);
if (first == null) {
first = stackNode;
top++;
return;
}
StackNode curr = first;
for (int i = 0; i < top; i++) {
curr = curr.next;
}
curr.next = stackNode;
}
public int pop(){
if (isEmpty()){
throw new RuntimeException("栈空");
}
StackNode curr = first;
for (int i = 0; i < top-1; i++) {
curr = curr.next;
}
int value = curr.next.value;
curr.next = null;
top--;
return value;
}
public void show(){
if (isEmpty()){
System.out.println("栈空");
return;
}
for (int i = top; i >= 0; i--) {
StackNode curr = first;
for (int j = 0; j < i; j++) {
curr = curr.next;
}
System.out.printf("第%d:%d\n",i,curr.value);
}
}
}
class StackNode{
int value;
StackNode next;
public StackNode(int value) {
this.value = value;
}
@Override
public String toString() {
return "StackNode{" +
"value=" + value +
'}';
}
}
|