# 前端基础之探索数据结构与算法系列（一）

• 前言

## 三、线性结构--栈

1. Javascript中的栈的实现

（2）确定操作方法：入栈方法（push），出栈方法（pop），预览栈顶方法（peek），清栈方法（clear），获取栈高方法（length）。具体实现如下：

``````function Stack() {
this.dataStore = [];
this.top = 0;

this.push = function ( element ) {
this.dataStore[this.top++] = element;
};

this.pop = function () {
return this.dataStore.splice(--this.top,1)[0];
};

this.peek = function () {
return this.dataStore[this.top-1];
};

this.length = function () {
return this.top;
};

this.clear = function () {
delete this.dataStore;
this.dataStore = [];
this.top = 0;
}
};``````
1. 栈的应用

（1）进制转化：将十进制整数转化为任意正整数进制。

``````function newBase( num, base ) {
var stack = new Stack();

// 除n取余
do {
stack.push(num % base);
num = Math.floor(num/base);
} while (num > 0);

// 倒写余数
var str = '';
for (var i = 0, length = stack.length(); i < length; i++) {
str += stack.pop();
};

return str;
};``````

(2)阶乘的迭代实现

``````function newFactorial( n ) {
var stack = new Stack();
while (n > 1) {
stack.push(n--)
};

var result = 1;
while (stack.length() > 0) {
result *= stack.pop();
};
return result;
}``````

(3)判断单词是否回文

``````function isPalindrome( words ) {
var stack = new Stack();

for (var i = 0; i < words.length; i++) {
stack.push(words[i]);
};

var rwords = '';
for (var i = 0, length = stack.length(); i < length; i++) {
rwords += s.pop();
};

if ( words === rwords ) {
return true;
} else {
return false;
};
};``````

(4)中缀表达式转化为后缀表达式（逆波兰表达式）

``````function reversePolishExpression( arithmetic ) {
var operater = new Stack();
var reverseExp = '';

for (var i = 0; i < arithmetic.length; i++) {
if ( '0123456789'.indexOf(arithmetic[i]) !== -1 ) {
reverseExp += arithmetic[i];
} else if ( '(+-*/'.indexOf(arithmetic[i]) !== -1 ) {
operater.push(arithmetic[i]);
} else if ( arithmetic[i] === ')' ) {
while ( '+-*/'.indexOf(operater.peek()) !== -1 ) {
reverseExp += operater.pop();
};
operater.pop();
};
};
return reverseExp;
};``````

## 四、线性结构--队列

1. Javascript中的队列的实现

``````function Queue() {
this.dataStore = [];
this.enqueue   = enqueue;
this.dequeue   = dequeue;
this.first     = first;
this.end       = end;
this.toString  = toString;
this.empty     = empty;

this.enqueue = function(element) {  //向队尾添加一个元素
this.dataStore.push(element);
}

this.dequeue = function() {      //删除队首的元素
return this.dataStore.shift();
}

this.getFirst = function() {  //读取队首元素
return this.dataStore[0];
}

this.getEnd = function() {    //读取队尾元素
return this.dataStore[this.dataStore.length - 1];
}

this.showAll = function() {   //显示队列中的所有元素
var retStr = "";
for (var i = 0; i < this.dataStore.length; ++i) {
retStr += this.dataStore[i] + "\n";
}
return retStr;
}

this.isEmpty = function() {      //判断队列是否为空
if (this.dataStore.length == 0) {
return true;
} else {
return false;
}
}
}

``````
1. 队列的应用

（1）优先队列（可实现javascript桥接模式）

``````function PriorityQueue() {

let items = [];

function QueueElement (element, priority){
this.element = element;//成员本身
this.priority = priority;  //优先级
}

this.enqueue = function(element, priority){
let queueElement = new QueueElement(element, priority);

for (let i=0; i<items.length; i++){
if (queueElement.priority <
items[i].priority){  //找到优先级数字比他大的那个元素

items.splice(i,0,queueElement);
// 插到该元素的前面
break;
}
}
items.push(queueElement); //{5}
}
};

//其他操作和普通队列是一样的

this.dequeue = function(){
return items.shift();
};

this.front = function(){
return items[0];
};

this.isEmpty = function(){
return items.length == 0;
};

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

this.print = function(){
for (let i=0; i<items.length; i++){
console.log(`\${items[i].element}  - \${items[i].priority}`);
}
};
}

let priorityQueue = new PriorityQueue();
priorityQueue.enqueue("zhao", 2);
priorityQueue.enqueue("wang", 1);
priorityQueue.enqueue("zhang", 1);
priorityQueue.enqueue("li", 2);
priorityQueue.enqueue("liu", 3);
priorityQueue.print();
//=>
//打印出的结果(按优先级排序)
wang  - 1
zhang  - 1
zhao  - 2
li  - 2
liu  - 3
``````

1 条评论