5.4栈的快速入门(使用链表模拟栈)
package com.atguigu04.stack;
import java.util.Scanner;
public class ArrayLinkedListStackDemo {
public static void main(String[] args) {
LinkedListStack linkedListStack = new LinkedListStack();
Scanner scanner = new Scanner(System.in);
boolean loop = true;
String str = "";
while (loop) {
System.out.println("show:显示栈的数据");
System.out.println("push:将一个数放进栈中:");
System.out.println("pop:将栈中的数据弹出:");
System.out.println("peek:返回栈顶的元素:");
System.out.println("exit:退出程序:");
System.out.println("请输入指令:");
str = scanner.nextLine();
switch (str) {
case "show" :
try {
linkedListStack.showLinkedListStack();
break;
} catch (Exception e) {
e.printStackTrace();
}
case "push":
System.out.println("请输入新节点的值:");
Node newNode = new Node(scanner.nextInt());
linkedListStack.LinkedListPush(newNode);
break;
case "pop":
try {
System.out.println(linkedListStack.LinkedListPop());
break;
} catch (Exception e) {
e.printStackTrace();
}
case "peek":
try {
System.out.println(linkedListStack.LinkedListPeek());
break;
} catch (Exception e) {
e.printStackTrace();
}
case "exit":
loop = false;
break;
default:
break;
}
}
}
}
class Node{
public int element;
public Node next = null;
public Node(int element){
this.element = element;
}
@Override
public String toString() {
return "Node{" +
"element=" + element +
'}';
}
}
class LinkedListStack {
public Node head = null;
public void LinkedListPush(Node newNode) {
if (head == null) {
head = newNode;
return;
}
newNode.next = head;
head = newNode;
System.out.println("数据入栈成功!");
return;
}
public int LinkedListPop() throws Exception {
if (head == null) {
throw new Exception("当前栈为空!");
}
Node temp = null;
temp = head.next;
int value = head.element;
head.next = null;
head = temp;
return value;
}
public int LinkedListPeek() throws Exception {
if (head == null) {
throw new Exception("当前链表为空");
}
int value = head.element;
return value;
}
public void showLinkedListStack() throws Exception {
if (head == null) {
throw new Exception("当前栈为空!");
}
Node temp = head;
while(true) {
if (temp == null) {
break;
}
System.out.println(temp.element);
temp = temp.next;
}
}
}