可以將 stack 想像成一個開口向上的容器(或盤子堆),只能從單方向放置元素
先放入的元素會堆積在底部,要 access 的話要先把後放入的元素先取出來
堆疊的主要操作方法有兩種,push & pop
作用分別為將元素添加入堆疊與將最近添加的元素移出堆疊
可以用 js array
跟 linked list
來寫
這裡用 linked list 下去修改
完整程式碼在這裡
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Stack {
constructor() {
this.head = null;
this.length = 0;
}
push(value) {
let newNode = new Node(value);
if (this.length === 0) {
this.head = newNode;
} else {
let currentNode = this.head;
while (currentNode.next !== null) {
currentNode = currentNode.next;
}
currentNode.next = newNode;
}
this.length++;
}
pop() {
if (this.length === 0) {
return null;
} else if (this.length === 1) {
let temp = this.head;
this.head = null;
this.length = 0;
return temp;
} else {
let currentNode = this.head;
for (let i = 1; i < this.length - 1; i++) {
currentNode = currentNode.next;
}
let temp = currentNode.next;
currentNode.next = null;
this.length--;
return temp;
}
}
}
let intStack = new Stack();
intStack.push(1);
intStack.push(3);
intStack.push(5);
console.log(intStack); // // length=3 [1,3,5]
intStack.pop();
console.log(intStack); // length=2 [1,3]
Queue 依循 先進先出 的原則,如同排隊
先添加的元素會隨著順序從表頭(front)移出,且只能從隊尾(tail/rear)添加新元素
可以用 js array
跟 linked list
來寫
這裡用 linked list 下去修改
完整程式碼在這裡
class Node{
constructor(value){
this.value = value;
this.next = null;
}
}
class Queue{
constructor(){
this.head= null;
this.length=0;
}
// remove elements from head position
dequeue(){
}
// add elements from the rear position
enqueue(value){
if(!this.head){
this.head = new Node(value);
}else{
let currentNode = this.head;
let newNode = new Node(value);
while(currentNode.next !== null){
currentNode = currentNode.next;
}
currentNode.next = new Node(value);
}
this.length++;
}
}
let groceryQueue = new Queue();
groceryQueue.enqueue("sushi");
groceryQueue.enqueue("tuna");
console.log(groceryQueue);
與 queue 相同, 但首尾相交
A hybrid type of Stack and Queue, which combines the features of stack and queue.
Deque allows us to add and remove elements from both ends.
Stack 跟 Queue 的混合體,可以從 front 處跟 tail 處添加跟移除元素
有興趣的話不妨試著用 js 寫看看~
data structure stacks
https://www.w3schools.com/dsa/dsa_data_stacks.php
stack
https://en.wikipedia.org/wiki/Stack_(abstract_data_type)
Stack overflow
https://en.wikipedia.org/wiki/Stack_overflow
call stack
https://developer.mozilla.org/en-US/docs/Glossary/Call_stack
Stack meaning in dsa
https://www.geeksforgeeks.org/stack-meaning-in-dsa/
Queue
https://en.wikipedia.org/wiki/Queue_(abstract_data_type)
deque in javascript
https://www.geeksforgeeks.org/deque-in-javascript/