看完,可以问自己几个问题:
1.请设计一个栈。保括push(),pop(),empty(),serch();(注意,synchronized用了没,)
2.栈的应用有哪些?比如。
3.题目:字符串匹配,逆波兰求值。
一.栈
1.基本概念:
通常将递归算法转换成非递归算法时需要使用到栈。
栈的定义:栈是一种只能在一端进行插入和删除操作的线性表。允许进行插入和删除的一端称为栈顶,另一端称为栈底。插入操作称为压栈或进栈。删除操作称为退栈或出栈。
特点:后进先出。
二.Java中栈官方的定义:
public
class Stack<E> extends Vector<E> {
public Stack() {
}
public E push(E item) {
addElement(item);
return item;
}
public synchronized E pop() {
E obj;
int len = size();
obj = peek();
removeElementAt(len - 1);
return obj;
}
public synchronized E peek() {
int len = size();
if (len == 0)
throw new EmptyStackException();
return elementAt(len - 1);
}
public boolean empty() {
return size() == 0;
}
public synchronized int search(Object o) {
int i = lastIndexOf(o);
if (i >= 0) {
return size() - i;
}
return -1;
}
private static final long serialVersionUID = 1224463164541339165L;
}
自己写的栈:
public class Stack<E> {
private static int MaxSize;
private Object data[];
private int top;
public Stack() {
MaxSize = 30;
data = new Object[MaxSize];
top = -1;
}
// 进栈
public E push(E item) {
top++;
data[top] = item;
return item;
}
// 出栈
public synchronized E pop() {
E obj = null;
if(top < 0) ;
else
{
obj = (E) data[top];
top--;
}
return obj;
}
public boolean empty() {
return top == -1;
}
public synchronized int search(Object o) {
for(int i = 0; i < top + 1; ++i)
{
if(o == data[i])
return i;
}
return -1;
}
}
三.栈的应用:
栈在Java中作为一个工具类,有很多用处,比如括号匹配,迷宫求解,表达式求值。
例如:
1.表达式求值(刷leetcode遇到的一个问题)
题目:Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
解答:
import java.util.Stack;
public class Test {
public static void main(String args[])
{
String tokens[] = {"14","5","2","+","/"};
int s = evalRPN(tokens);
System.out.println(s);
}
public static int evalRPN(String[] tokens) {
Stack<String> num = new Stack<String>();
String result = "";
if (tokens.length == 1)
return Integer.parseInt(tokens[0]);
for (String str : tokens) {
if (str.compareTo("+") != 0 && str.compareTo("-") !=0
&& str.compareTo("*") !=0 && str.compareTo("/") !=0) {
num.push(str);
} else {
String r = num.pop();
String l = num.pop();
result = calculation(l, r, str);
num.push(result);
}
}
result = num.pop();
return Integer.parseInt(result);
}
public static String calculation(String l, String r, String op) {
StringBuffer resultStr = new StringBuffer();
int left = Integer.parseInt(l);
int right = Integer.parseInt(r);
int result = 0;
switch(op)
{
case "+":
result = left + right;
break;
case "-":
result = left - right;
break;
case "*":
result = left * right;
break;
case "/":
result = left / right;
break;
}
resultStr.append(result);
return resultStr.toString();
}
}
2.判断括号:
public class Test {
public static void main(String args[])
{
String ch[] = {"[","(","]",")","[",")","("};
Stack<String> chStack = new Stack<String>();
int i = 0;
boolean flag = true;
if(ch.length == 1) flag = false;
while(i < ch.length)
{
if(flag == false) break;
switch(ch[i])
{
case "[":
chStack.push(ch[i]);
break;
case "]":
if(chStack.empty()) flag = false;
else{
String s = chStack.pop();
if(!s.equals("[")) flag = false;
}
break;
case "(":
chStack.push(ch[i]);
break;
case ")":
if(chStack.empty()) flag = false;
else{
String s = chStack.pop();
if(!s.equals("(")) flag = false;
}
break;
}
i++;
}
if( (flag == false) || (chStack.size() > 0) ) System.out.println("Error!");
else System.out.println("Right!");
}
}
有错误或者更高效的代码,欢迎指出。