오늘은 알고리즘 공부 다시 할겸 JS로 큐, 스택 구현을 해보았다. 문제도 풀고..
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class Queue {
constructor(data) {
this.first = new Node(data)
this.size = 1
this.capacity = 5;
}
enqueue(data) {
const node = new Node(data);
if (!this.first) {
this.first = node;
} else if (this.size === this.capacity) return console.log('queue is full')
else {
let n = this.first;
while (n.next) {
n = n.next;
}
n.next = node;
this.size += 1;
}
}
dequeue() {
if (!this.size) return console.log('queue is empty');
else {
const first = this.first;
this.first = this.first.next; // next 값을 첫 값으로
this.size -= 1;
return first;
}
}
embed(data, t){
if(!this.size === this.capacity) return console.log('queue is full');
const node = new Node(data);
let i = 0;
let n = this.first;
while(i++ < t-1){
n = n.next;
}
const temp = n.next;
n.next = node;
n.next.next = temp;
this.size += 1;
}
}
class Stack{
constructor(data) {
this.first = new Node(data);
this.size = 1;
this.capacity = 5;
}
push(data){
if(this.size === this.capacity) return console.log('stack is full');
else{
const node = new Node(data);
const temp = this.first;
this.first = node;
this.first.next = temp;
this.size += 1;
}
}
isEmpty(){
return this.size === 0;
}
pop(){
if(!this.size) return console.log('stack is empty');
else{
const temp = this.first;
this.first = this.first.next;
this.size -= 1;
return temp;
}
}
embed(data, t){
if(this.size === this.capacity) return console.log('stack is full');
else{
const node = new Node(data);
let i = 0;
let n = this.first;
while(i++ < t-1){
n = n.next;
}
const temp = n.next;
n.next = node;
n.next.next = temp;
this.size += 1;
}
}
}
const stack1 = new Stack();
const stack2 = new Stack();
function enqueueByStack(data){
stack1.push(data);
}
function dequeueByStack(){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
return stack2.pop();
}
enqueueByStack(1);
enqueueByStack(2);
enqueueByStack(3);
enqueueByStack(4);
console.log(dequeueByStack()); //1
console.log(dequeueByStack()); //2
console.log(dequeueByStack()); //3
function convert(n){
const stack = new Stack();
while(n >= 2){
stack.push(n % 2);
n = Math.floor(n / 2);
};
stack.push(1); // 마지막
let result = '';
while(!stack.isEmpty()){
result += stack.pop().data.toString();
}
return result;
}