Skip to content

Commit 9588d55

Browse files
committed
[zh-tw] Add Stack
1 parent f398ff0 commit 9588d55

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

zh-tw/basics_data_structure/stack.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Stack - 堆疊
2+
3+
堆疊是一種 LIFO(Last In First Out) 的資料結構,常用方法有添加元素,讀Stack頂元素,彈出(pop) Stack頂元素,判斷堆疊是否為空。
4+
5+
## 程式碼實現
6+
7+
### Python
8+
```python
9+
stack = []
10+
len(stack) # size of stack
11+
12+
# more efficient stack
13+
import collections
14+
stack = collections.deque()
15+
```
16+
17+
`list`作為最基本的`python`資料結構之一, 可以很輕松的實現`stack`。 如果需要更高效的`stack`, 建議使用`deque`
18+
19+
#### Methods
20+
21+
- `len(stack) != 0` - 判斷`stack`是否weikong
22+
- `stack[-1]` - 取堆疊頂元素,不移除
23+
- `pop()` - 移除堆疊頂元素並返回該元素
24+
- `append(item)` - 向堆疊頂添加元素
25+
26+
27+
### Java
28+
29+
```java
30+
Deque<Integer> stack = new ArrayDeque<Integer>();
31+
s.size(); // size of stack
32+
```
33+
34+
JDK doc 中建議使用`Deque`代替`Stack`實現堆疊,因為`Stack`繼承自`Vector`,需要`synchronized`,性能略低。
35+
36+
#### Methods
37+
38+
- `boolean isEmpty()` - 判斷堆疊是否為空,若使用 Stack 類構造則為 empty()
39+
- `E peek()` - 取堆疊頂元素,不移除
40+
- `E pop()` - 移除堆疊頂元素並返回該元素
41+
- `E push(E item)` - 向堆疊頂添加元素

0 commit comments

Comments
 (0)