import java.util.Iterator;
public class Stack<T> implements Iterable<T> {
//记录首结点
private Node head;
//栈中元素的个数
private int N;
public Stack() {
head = new Node(null, null);
N = 0;
}
//判断当前栈中元素个数是否为0
public boolean isEmpty() {
return N == 0;
}
// 清空栈
public void clear() {
head.next = null;
head.item = null;
N = 0;
}
//把t元素压入栈
public void push(T t) {
Node oldNext = head.next;
Node node = new Node(t, oldNext);
head.next = node;
N++;
}
//弹出栈顶元素
public T pop() {
Node oldNext = head.next;
if (oldNext == null) {
return null;
}
head.next = head.next.next;
N--;
return oldNext.item;
}
// 获取栈中元素的个数
public int size() {
return N;
}
@Override
public Iterator iterator() {
return new SIterator();
}
private class SIterator implements Iterator<T> {
private Node n = head;
@Override
public boolean hasNext() {
return n.next != null;
}
@Override
public T next() {
n = n.next;
return n.item;
}
}
private class Node {
public T item;
private Node next;
public Node(T item, Node next) {
this.item = item;
this.next = next;
}
}
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
stack.push("a");
stack.push("b");
stack.push("c");
stack.push("d");
for (String str : stack) {
System.out.print(str + " ");
}
System.out.println();
System.out.println("--------------------");
String result = stack.pop();
System.out.println(result);
System.out.println(stack.size());
stack.clear();
String str = "(上海(长安)())";
boolean match = isMatch(str);
System.out.println(str + "中的括号是否匹配:" + match);
//中缀表达式3*(17-15)+18/6的逆波兰表达式如下
String[] notation = {"3", "17", "15", "-", "*","18", "6","/","+"};
int n = caculate(notation);
System.out.println("逆波兰表达式的结果为:"+n);
}
括号匹配问题
/**
*给定一个字符串,里边可能包含"()"小括号和其他字符,请编写程序检查该字符串的中的小括号是否成对出现。
*例如:
* "(上海)(长安)":正确匹配
* "上海((长安))":正确匹配
* "上海(长安(北京)(深圳)南京)":正确匹配
* "上海(长安))":错误匹配
* "((上海)长安":错误匹配
* 判断str中的括号是否匹配
* @param str 括号组成的字符串
* @return 如果匹配,返回true,如果不匹配,返回false
*/
public static boolean isMatch(String str) {
Stack<Character> characters = new Stack<>();
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == '(') {
characters.push(chars[i]);
}
if (chars[i] == ')') {
Character t = characters.pop();
// 防止 给定的字符串中就没有( 只有 )
if(t==null) return false;
}
}
return characters.size() == 0;
}
逆波兰表达式求值问题
/**
* @param notaion 逆波兰表达式的数组表示方式
* @return 逆波兰表达式的计算结果
*/
public static int caculate(String[] notaion){
Stack<Integer> integers = new Stack<>();
for (String str :notaion){
Integer o1= null;
Integer o2=null;
switch (str){
case "+":
o1=integers.pop();
o2=integers.pop();
integers.push(o1+o2);
break;
case "-":
o1=integers.pop();
o2=integers.pop();
integers.push(o2-o1);
break;
case "*":
o1=integers.pop();
o2=integers.pop();
integers.push(o2*o1);
break;
case "/":
o1=integers.pop();
o2=integers.pop();
integers.push(o2/o1);
break;
default:
integers.push(Integer.valueOf(str));
break;
}
}
return integers.pop();
}