Skip to content

Commit ee085d3

Browse files
committed
update Candy-021
1 parent cc10aed commit ee085d3

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

Candy-021/README.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
## 編號:CANDY-021
2+
3+
### 程式語言:JavaScript
4+
5+
#### 題目:實作 Stack 資料結構
6+
7+
```js
8+
class Stack {
9+
constructor() {
10+
this.items = [];
11+
}
12+
13+
push(element) {
14+
if (element !== undefined) {
15+
this.items.push(element);
16+
}
17+
}
18+
19+
pop() {
20+
return this.items.pop();
21+
}
22+
23+
get size() {
24+
return this.items.length;
25+
}
26+
}
27+
28+
// 用陣列來儲存堆疊的元素
29+
// 添加元素到堆疊頂端
30+
// 移除並返回堆疊頂端的元素
31+
// 獲取堆疊中元素的數量
32+
33+
const stack = new Stack();
34+
stack.push(123);
35+
stack.push(456);
36+
stack.push();
37+
console.log(stack.size); // 印出 2
38+
39+
const item = stack.pop(); // 取出元素
40+
console.log(item); // 印出 456
41+
42+
stack.pop(); // 繼續取出元素
43+
console.log(stack.size); // 印出 0
44+
```

0 commit comments

Comments
 (0)