数组实现栈
package com.weeks.stack;
import java.util.Scanner;
public class ArrayStackDemo {
public static void main(String[] args) {
ArrayStack arrayStack = new ArrayStack(4);
Scanner scanner = new Scanner(System.in);
char key = ' ';
boolean loop = true;
while(loop){
System.out.println("\n栈操作方法菜单:\n" +
"1 push 数据入栈\n" +
"2 pop 数据出栈\n" +
"3 list 显示栈中数据\n" +
"4 exit 退出程序\n");
System.out.print("请输入你的选择:");
key = scanner.next().charAt(0);
switch (key){
case '1':
System.out.print("请输入一个整数:");
int value = scanner.nextInt();
arrayStack.push(value);
break;
case '2':
try {
int res = arrayStack.pop();
System.out.printf("本次出栈的数据为:%d\n", res);
} catch (Exception e) {
System.out.println(e);
}
break;
case '3':
arrayStack.list();
break;
case '4':
scanner.close();
loop = false;
break;
default:
break;
}
}
System.out.println("退出程序~~~");
}
}
class ArrayStack{
private int maxSize;
private int top = -1;
private int[] stack;
public ArrayStack(int maxSize){
this.maxSize = maxSize;
this.stack = new int[this.maxSize];
}
public boolean isFull(){
return top == maxSize - 1;
}
public boolean isEmpty(){
return top == -1;
}
public void push(int value){
if(isFull()){
System.out.println("已满栈,无法入栈!!!");
return;
}
stack[++top] = value;
}
public int pop(){
if(isEmpty()){
throw new RuntimeException("栈已空,没有数据可以出栈!!!");
}
int res = stack[top];
top--;
return res;
}
public void list(){
if(isEmpty()){
System.out.println("栈已空,没有数据可遍历!!!");
return;
}
for(int i = top; i > -1; i--){
System.out.printf("arr[%d]=%d\n", i, stack[i]);
}
}
}
单链表实现栈
package com.weeks.stack;
import java.util.Scanner;
public class LinkedListStackDemo {
public static void main(String[] args) {
LinkedListStack stack = new LinkedListStack();
Scanner scanner = new Scanner(System.in);
char key = ' ';
boolean loop = true;
while(loop){
System.out.println("\n栈操作方法菜单:\n" +
"1 push 数据入栈\n" +
"2 pop 数据出栈\n" +
"3 list 显示栈中数据\n" +
"4 exit 退出程序\n");
System.out.print("请输入你的选择:");
key = scanner.next().charAt(0);
switch (key){
case '1':
System.out.print("请输入一个整数:");
int value = scanner.nextInt();
stack.push(value);
break;
case '2':
try {
int res = stack.pop();
System.out.printf("本次出栈的数据为:%d\n", res);
} catch (Exception e) {
System.out.println(e);
}
break;
case '3':
stack.list();
break;
case '4':
scanner.close();
loop = false;
break;
default:
break;
}
}
System.out.println("退出程序~~~");
}
}
class LinkedListStack{
private Node head = new Node(0);
public boolean isEmpty(){
return head.getNext() == null;
}
public void push(int value){
Node node = new Node(value);
node.setNext(head.getNext());
head.setNext(node);
}
public int pop(){
if (isEmpty()){
throw new RuntimeException("栈已空,没有数据可以出栈!!!");
}
int res = head.getNext().getData();
head.setNext(head.getNext().getNext());
return res;
}
public void list(){
if(isEmpty()){
System.out.println("栈已空,不可遍历!!!");
return;
}
Node cur = head.getNext();
while(cur != null){
System.out.println(cur);
cur = cur.getNext();
}
}
}
class Node{
private int data;
private Node next;
public Node(int data){
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
@Override
public String toString() {
return "Node = " + data;
}
}
栈实现综合计算器
中缀表达式
package com.weeks.stack.calculator;
public class CalculatorDemo {
public static void main(String[] args) {
LinkedListStack numStack = new LinkedListStack();
LinkedListStack operatorStack = new LinkedListStack();
String expression = "700+2*6-2";
int index = 0;
char curChar = ' ';
String keepNum = "";
while(index < expression.length()){
curChar = expression.substring(index, index+1).charAt(0);
if(operatorStack.isOperator(curChar)){
if (operatorStack.isEmpty()){
operatorStack.push(curChar);
}else if(operatorStack.priority(curChar) <= operatorStack.priority((char) operatorStack.getTop())){
char opr = (char) operatorStack.pop();
int num1 = 0;
int num2 = 0;
try {
num1 = numStack.pop();
num2 = numStack.pop();
} catch (Exception e) {
System.out.println(e.getMessage());
}
int res = numStack.calculate(num1, num2, opr);
numStack.push(res);
operatorStack.push(curChar);
}else{
operatorStack.push(curChar);
}
}else{
if(index == expression.length() - 1){
numStack.push(curChar - 48);
}else{
keepNum += curChar;
char nextChar = expression.substring(index+1, index+2).charAt(0);
if(operatorStack.isOperator(nextChar)){
numStack.push(Integer.parseInt(keepNum));
keepNum = "";
}
}
}
index++;
}
while(true){
if(operatorStack.isEmpty()){
break;
}
char opr = (char) operatorStack.pop();
int num1 = numStack.pop();
int num2 = numStack.pop();
int res = numStack.calculate(num1, num2, opr);
numStack.push(res);
}
System.out.printf("计算的结果%s = %d", expression, numStack.pop());
}
}
class LinkedListStack{
private Node head = new Node(-1);
public boolean isEmpty(){
return head.getNext() == null;
}
public void push(int value){
Node node = new Node(value);
node.setNext(head.getNext());
head.setNext(node);
}
public int pop(){
if (isEmpty()){
throw new RuntimeException("栈已空,没有数据可以出栈!!!");
}
int res = head.getNext().getData();
head.setNext(head.getNext().getNext());
return res;
}
public void list(){
if(isEmpty()){
System.out.println("栈已空,不可遍历!!!");
return;
}
Node cur = head.getNext();
while(cur != null){
System.out.println(cur);
cur = cur.getNext();
}
}
public int getTop(){
if(head.getNext() == null){
throw new RuntimeException("栈空,没有栈顶元素!!!");
}
return head.getNext().getData();
}
public int priority(char operator){
if (operator == '*' || operator == '/'){
return 1;
}else if(operator == '+' || operator == '-'){
return 0;
}else{
throw new RuntimeException("输入的不是操作符!!!");
}
}
public boolean isOperator(char operator){
return operator == '*' || operator == '/' || operator == '+' || operator == '-';
}
public int calculate(int num1, int num2, char operator){
int res = 0;
switch (operator){
case '+':
res = num1 + num2;
break;
case '-':
res = num2 - num1;
break;
case '*':
res = num1 * num2;
break;
case '/':
res = num2 / num1;
break;
default:
break;
}
return res;
}
}
class Node{
private int data;
private Node next;
public Node(int data){
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
@Override
public String toString() {
return "Node = " + data;
}
}
逆波兰表达式(后缀表达式)
package com.weeks.stack.calculator;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class AntiPolandExpressionCalculate {
public static void main(String[] args) {
String inSuffixExpression = "3*(400+5)-3+6*7/2+6";
List<String> strings = changeInSuffixToList(inSuffixExpression);
System.out.println(strings);
List<String> suffixList = parseToSuffixExpression(strings);
System.out.println(suffixList);
int result = calculate(suffixList);
System.out.printf("%s = %d", inSuffixExpression, result);
}
public static List<String> getList(String suffixExpression){
String[] splits = suffixExpression.split(" ");
List<String> strings = new ArrayList<>();
for(String str : splits){
strings.add(str);
}
return strings;
}
public static int calculate(List<String> strings){
Stack<String> nums = new Stack<>();
for(String item : strings){
if(item.matches("\\d+")){
nums.add(item);
}else{
int num2 = Integer.parseInt(nums.pop());
int num1 = Integer.parseInt(nums.pop());
int res = 0;
if(item.equals("+")){
res = num1 + num2;
}else if(item.equals("-")){
res = num1 - num2;
}else if(item.equals("*")){
res = num1 * num2;
}else if(item.equals("/")){
res = num1 / num2;
}else{
throw new RuntimeException("表达式的符号有误,请检查!!!");
}
nums.push("" + res);
}
}
return Integer.parseInt(nums.pop());
}
public static List<String> changeInSuffixToList(String inSuffixExpression){
List<String> strings = new ArrayList<>();
int index = 0;
char curChar = ' ';
String num = "";
while(index < inSuffixExpression.length()){
curChar = inSuffixExpression.substring(index, index+1).charAt(0);
if(curChar < 48 || curChar > 57){
strings.add(curChar + "");
}else{
if(index == inSuffixExpression.length() - 1){
strings.add(curChar + "");
}else{
num += curChar;
char next = inSuffixExpression.substring(index+1, index+2).charAt(0);
if(next < 48 || next > 57){
strings.add(num);
num = "";
}
}
}
index++;
}
return strings;
}
public static List<String> parseToSuffixExpression(List<String> inSuffixList){
Stack<String> oprStack = new Stack<>();
List<String> resList = new ArrayList<>();
for(String item : inSuffixList){
if(item.matches("\\d+")){
resList.add(item);
}else{
if(oprStack.isEmpty() || item.equals("(")){
oprStack.push(item);
}else{
if(item.equals(")")){
while(!(oprStack.peek().equals("("))){
resList.add(oprStack.pop());
}
oprStack.pop();
}else if(oprStack.peek().equals("(")){
oprStack.push(item);
}else {
int priority = Priority.getPriority(item);
if( priority <= Priority.getPriority(oprStack.peek())) {
while(!oprStack.isEmpty() && priority <= Priority.getPriority(oprStack.peek())) {
resList.add(oprStack.pop());
}
oprStack.push(item);
}else{
oprStack.push(item);
}
}
}
}
}
while(!oprStack.isEmpty()){
resList.add(oprStack.pop());
}
return resList;
}
}
class Priority{
private static final int ADD = 1;
private static final int SUB = 1;
private static final int MUL = 2;
private static final int DIV = 2;
public static int getPriority(String key){
switch (key){
case "+":
return ADD;
case "-":
return SUB;
case "*":
return MUL;
case "/":
return DIV;
default:
throw new RuntimeException("没有该类型的操作符!!!");
}
}
}