1、基本介绍
2、应用实例(链表模拟栈)
package stack;
import java.util.Scanner;
public class LinkedListStack {
public static void main(String[] args) {
LinkedStack stack = new LinkedStack(1024);
Scanner scanner = new Scanner(System.in);
boolean loop = true;
char op;
int val = 0;
String temp = "";
while(loop) {
System.out.println("\n入栈操作(i)");
System.out.println("出栈操作(o)");
System.out.println("打印栈栈(p)");
System.out.println("查看栈是否空(e)");
System.out.println("退出程序(q)~");
System.out.print("请选择你要执行的操作:");
op = scanner.next().charAt(0);
switch (op) {
case 'i':
System.out.print("请输入要入栈的元素:");
val = scanner.nextInt();
stack.push(val);
break;
case 'o':
val = stack.pop();
System.out.println("出栈元素:" + val);
break;
case 'p':
stack.print();
break;
case 'e':
temp = ! stack.isEmpty() ? "栈不为空!" : "栈为空!";
System.out.println(temp);
break;
default:
scanner.close();
loop = false;
break;
}
}
}
}
class LinkedStack {
public Node top; // 栈指针,开始指向null
public int maxSize;
public LinkedStack(int maxSize) {
this.maxSize = maxSize;
this.top = null;
}
// 栈节点类
public static class Node{
public int data;
public Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public void push(int val) {
Node newNode = new Node(val);
newNode.next = top;
top = newNode;
System.out.println("入栈成功~");
}
public int pop() {
if (isEmpty()) {
throw new RuntimeException("栈空,出栈失败!");
}
int temp = top.data;
top = top.next;
return temp;
}
public void print() {
if (isEmpty()) {
throw new RuntimeException("栈空,出栈失败!");
}
System.out.print("栈元素:");
Node temp = top;
while(temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
public boolean isEmpty() {
if (top == null) {
return true;
}
return false;
}
}