原理:栈是一种先进后出的数据结构,底层可以用链表和数组实现。
代码:
package com.chenqing.test.linearList.stack;
import java.util.Iterator;
public class Realization <T> implements Iterable<T>{
private Node head;
private int n;
public Realization() {
this.head = new Node(null, null);
this.n = 0;
}
public boolean isEmpty(){
return this.n == 0;
}
public int size(){
return this.n;
}
public void push(T t){
Node oldFirst = this.head.next;
Node newNode = new Node(t, oldFirst);
this.head.next = newNode;
this.n++;
}
public T pop(){
Node oldFirst = this.head.next;
if(oldFirst==null){
return null;
}
this.head.next = oldFirst.next;
this.n--;
return oldFirst.data;
}
@Override
public Iterator<T> iterator() {
return new MyselfIterator();
}
private class MyselfIterator implements Iterator<T>{
private Node n;
public MyselfIterator() {
this.n = head;
}
@Override
public boolean hasNext() {
return n.next != null;
}
@Override
public T next() {
n=n.next;
return n.data;
}
}
private class Node{
T data;
Node next;
public Node(T data, Node next) {
this.data = data;
this.next = next;
}
}
}
示例:
1、括号匹配问题:
public void testMatch() {
String str = "中正因为(中中)(里))";
boolean match = isMatch(str);
System.out.println(match);
}
private boolean isMatch(String str) {
Realization<String> strings = new Realization<>();
for (int i = 0; i < str.length(); i++) {
String curStr = str.charAt(i) + "";
if (curStr.equals("(")) {
strings.push(str.charAt(i) + "");
} else if (curStr.equals(")")) {
String pop = strings.pop();
if (pop == null) {
return false;
}
}
}
if (strings.isEmpty()) {
return true;
} else {
return false;
}
}
2、逆波兰表达式计算:
代码:
public void postfix() {
String expression = "34*23+4/2-22+(45+33)";
String[] expressionArr = {"34", "23", "*", "4", "2", "/", "+", "22", "-", "45", "33", "+", "+"};
Realization<Integer> integers = new Realization<>();
for (int i = 0; i < expressionArr.length; i++) {
String curr = expressionArr[i];
Integer pop1=0;
Integer pop2 = 0;
switch (curr){
case "+":
pop1 = integers.pop();
pop2 = integers.pop();
int addVal = pop2 + pop1;
integers.push(addVal);
break;
case "-":
pop1 = integers.pop();
pop2 = integers.pop();
int eVal = pop2 - pop1;
integers.push(eVal);
break;
case "*":
pop1 = integers.pop();
pop2 = integers.pop();
int xVal = pop2 * pop1;
integers.push(xVal);
break;
case "/":
pop1 = integers.pop();
pop2 = integers.pop();
int cVal = pop2 / pop1;
integers.push(cVal);
break;
default:
integers.push(Integer.parseInt(curr));
}
}
Integer result = integers.pop();
System.out.println(result);
}