-
Notifications
You must be signed in to change notification settings - Fork 47
/
Stack.java
142 lines (130 loc) · 2.94 KB
/
Stack.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import java.util.Iterator;
import java.util.Scanner;
public class Stack<Item> implements Iterable<Item>
{
private Node first; // 栈顶(最近添加的元素)
private int N; // 元素数量
private class Node
{ // 定义了结点的镶嵌类
Item item;
Node next;
}
public boolean isEmpty()
{
return first == null; // Or: N == 0.
}
public int size()
{
return N;
}
public void push(Item item)
{ //从栈顶添加元素
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
N++;
}
public Item pop()
{ // 从栈顶删除元素
Item item = first.item;
first = first.next;
N--;
return item;
}
public Iterator<Item> iterator()
{
return new ListIterator();
}
private class ListIterator implements Iterator<Item> //实现迭代器
{
private Node current = first;
public boolean hasNext()
{
return current != null;
}
public void remove()
{
//null
}
public Item next()
{
Item item = current.item;
current = current.next;
return item;
}
}
public static void main(String[] args)
{
// Stack<Double> stack = new Stack<Double>();
// String data = "10.0 20.0 30.0 40.0";
// Scanner sc = new Scanner(data);
// while (sc.hasNext())
// {
// stack.push(sc.nextDouble());
// }
// sc.close();
//
// for (Double value : stack)
// {
// System.out.println(value);
// }
Stack<String> ops = new Stack<String>();
Stack<Double> vals = new Stack<Double>();
String expression = "( 3 + ( 4 * 5 ) * 10 )";
Scanner sc = new Scanner(expression);
while (sc.hasNext())
{
String s = sc.next();
switch(s)
{
case "(":
break;
case "+":
ops.push(s);
break;
case "-":
ops.push(s);
break;
case "*":
ops.push(s);
break;
case "/":
ops.push(s);
break;
case "sqrt":
ops.push(s);
break;
case ")":
String op = ops.pop();
double v = vals.pop();
if(op.equals("+"))
{
v = vals.pop() + v;
}
else if(op.equals("-"))
{
v = vals.pop() - v;
}
else if(op.equals("*"))
{
v = vals.pop() * v;
}
else if(op.equals("/"))
{
v = vals.pop() / v;
}
else if(op.equals("sqrt"))
{
v = Math.sqrt(v);
}
vals.push(v);
break;
default:
vals.push(Double.parseDouble(s));
}
}
sc.close();
System.out.println(vals.pop());
}
}