// stack
class Stack {
constructor(){
this.stack = [];
}
push(item){
this.stack.push(item);
}
pop(){
var item = this.stack.pop();
return item;
}
peek(){
return this.stack[this.getCount() - 1];
}
getCount(){
return this.stack.length;
}
isEmpty(){
return this.getCount() === 0;
}
}
let stack = new Stack();
stack.push(10);
stack.push('twenty');
console.log(stack.pop());
console.log(stack.pop());
console.log(stack.isEmpty());
// queue
class Queue {
constructor(){
this.queue = [];
}
enQueue(item){
this.queue.push(item);
}
deQueue(){
var item = this.queue.shift();
return item;
}
header(){
return this.queue[0];
}
getCount(){
return this.queue.length;
}
isEmpty(){
return this.getCount() === 0;
}
}
//list
class Node {
constructor(v, next) {
this.value = v;
this.next = next;
}
}
class LinkList {
constructor(){
this.size = 0;
this.dummyNode = new Node(null, null);
}
find(header, index, currentIndex){
if (index == currentIndex) return header;
return this.find(header.next, index, currentIndex + 1);
}
addNode(v, index) {
this.checkIndex(index);
let prev = this.find(this.dummyNode, index, 0);
prev.next = new Node(v, prev.next);
this.size++;
return prev.next;
}
removeNode(index, isLast) {
this.checkIndex(index);
index = isLast ? index - 1 : index;
let prev = this.find(this.dummyNode, index, 0);
let node = prev.next;
prev.next = node.next;
node.next = null;
this.size--;
return node;
}
checkIndex(index){
if (index < 0 || index > this.index)
throw Error('Index error');
}
}
console