4. Stack & Queue Basic
16740 ワード
1. Stack
LIFO(Last In First Out)
コード実装
class StackNode {
constructor(val) {
this.val = val;
this.next = null;
}
}
class Stack {
constructor() {
this.top = null;
this.size = 0;
}
push(val) {
if(this.size === 0) {
this.top = new StackNode(val);
} else {
const pushNode = new StackNode(val);
pushNode.next = this.top;
this.top = pushNode;
}
this.size ++;
}
getTop() {
return this.top.val;
}
pop() {
if(this.size === 0) return null;
const popNode = this.top;
this.top = this.top.next;
this.size--;
return popNode.val;
}
}
const stack = new Stack();
stack.push('a');
stack.push('b');
stack.push('c');
console.log(stack.getTop());
console.log(stack.pop());
console.log(stack.getTop());
2. Queue
FIFO(Last In First Out)
class QueueNode {
constructor(val) {
this.val = val;
this.next = null;
}
}
class Queue {
constructor() {
this.front = null;
this.back = null;
this.size = 0;
}
enqueue(val) {
const newNode = new QueueNode(val);
if(this.size === 0) {
this.front = newNode;
this.back = newNode;
} else {
this.back.next = newNode;
this.back = newNode;
}
this.size++;
// a -> b -> c -> d
// F B
}
dequeue() {
if(this.size === 0) {
return null;
}
const removedNode = this.front;
if (this.size === 1) {
this.back = null;
}
this.front = this.front.next;
this.size--;
return removedNode.val;
}
}
const queue = new Queue();
queue.enqueue('a');
queue.enqueue('b');
queue.enqueue('c');
console.log(queue.front);
console.log(queue.back);
queue.dequeue();
queue.dequeue();
queue.dequeue();
queue.dequeue();
queue.dequeue();
console.log(queue.front);
注意:codebyte-stack&queueReference
この問題について(4. Stack & Queue Basic), 我々は、より多くの情報をここで見つけました https://velog.io/@kimkevin90/4.-Stack-Queue-Basicテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol