Skip to content

Commit 3c5c6f1

Browse files
committed
实现 Stack
1 parent 5a62773 commit 3c5c6f1

File tree

1 file changed

+32
-18
lines changed
  • group04/24658892/learnjava/src/main/java/com/coding/basic

1 file changed

+32
-18
lines changed
Lines changed: 32 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,36 @@
11
package com.coding.basic;
22

3+
import java.util.EmptyStackException;
4+
35
public class Stack {
4-
private ArrayList elementData = new ArrayList();
5-
6-
public void push(Object o){
7-
}
8-
9-
public Object pop(){
10-
return null;
11-
}
12-
13-
public Object peek(){
14-
return null;
15-
}
16-
public boolean isEmpty(){
17-
return false;
18-
}
19-
public int size(){
20-
return -1;
21-
}
6+
7+
private ArrayList elementData = new ArrayList();
8+
private int size = 0;
9+
10+
public void push(Object o) {
11+
elementData.add(o);
12+
size++;
13+
}
14+
15+
public Object pop() {
16+
if (isEmpty()) {
17+
throw new EmptyStackException();
18+
}
19+
return elementData.remove(--size);
20+
}
21+
22+
public Object peek() {
23+
if (this.isEmpty()) {
24+
throw new EmptyStackException();
25+
}
26+
return elementData.get(size - 1);
27+
}
28+
29+
public boolean isEmpty() {
30+
return size == 0;
31+
}
32+
33+
public int size() {
34+
return size;
35+
}
2236
}

0 commit comments

Comments
 (0)