# 算法和数据结构在JS中的运用（三）

#### 队列(Queue)

1. 特点：先进先出（FIFO）
2. 举例
/*
*适用于餐厅取号
**/
const queue = [];
let num = 0;

push= () => {
num += 1;
queue.push.call(queue,num);
}
pop = () => {
const n = queue.shift.call(queue); // 等价于 queue.shift()
// if n === undefined 没处理
if(n === undefined){
return;
}
};

##### 栈（Stack）
1. 特点：先进后出（LIFO）
2. 举例
stack = () => {
let items = [];

this.push = (element) => {
items.push(element);
}

this.pop = () => {
return items.pop();
}

this.peek = () => {
return items[items - 1];
}

this.empty = () => {
return items.length === 0;
}

this.size = () => {
return items.length;
}

this.clear = () => {
items = [];
}

this.print = () => {
console.log(items.toString());
}
}


const createList = value => {
return createNode(value);
}

const appendList = (list,value) => {
const node = createNode(value);
let x = list;
while(x.next){
x = x.next;
}
x.next = node;
return node;
}

const removeFromList = (list,node) => {
let x = list;
let p = node;
while(x !== node && x !== null){
p = x;
x = x.next;
}
if( x === null ) return false;
else if(x === p){
p = x.next;
return p;
}else{
p.next = x.next;
return list;
}
}

const createNode = value => {
return {
data: value,
next: null
};
};

const travelList = (list,fn) => {
let x = list;
while( x !== null){
fn(x);
x = x.next;
}
}

const list = createList(10);
const node2 = appendList(list,20);
const node3 = appendList(list,30);
const node4 = appendList(list,40);
travelList(list,node => {
console.log(node.data);
});

##### 树（tree）
1. 举例
/*
*适用于中国的省市区
*公司的组织架构
*网页中的节点
**/
const createTree = value => {
return {
data: value,
children: null,
parent: null
}
}

const addChild = (node,value) => {
const newNode = {
data: value,
children: null,
parent: node
};
node.children = node.children || [];
node.children.push(newNode);
return newNode;
}

const travel = (tree,fn) => {
fn(tree);
if(!tree.children){
return;
}else if(tree.children){
for(let i = 0; i < tree.children.length; i++){
const result = find(tree.children[i], node);
if(reuslt){
return result;
}
}
return undefined;
}else{
return undefined;
}
};

const removeNode = (tree,node) => {
const siblings = node.parent.children;
let index = 0;
for(let i = 1; i < siblings.length ; i++){
if (siblings[i] === node) {
index = i;
}
}
siblings.splice(index, 1);
}

const tree = createTree(10);
console.log(tree);

const fn = node => {
console.log(node.data);
};

removeNode(tree, node5);
console.log(tree);


10-15 1万+
08-13 2150
04-18 646
04-08 1078
08-24 42
08-14 360
03-07 352
11-26 193
06-24 146
01-04 70
03-22 222
06-19 258
01-04
09-19