學習編程已經有很長的時間了程腹,雖然能獨立的完成一些簡單的項目嚼吞,但在遇到一些難點的時候嗎,仍感到自身算法方面的不足刽严,所以特此記錄自己學習數據結構與算法的過程昂灵。
1、棧結構
特點: 后進先出舞萄。
Js代碼實現:
class Stack {
constructor() {
this.item = [];
}
push(val) {
this.item.push(val);
}
pop() {
return this.item.pop();
}
peek() {
return this.item[this.item.length - 1];
}
isEmpty() {
return this.item.length == 0;
}
size() {
return this.item.length;
}
toString() {
let result = '';
for (let i = 0; i < this.item.length; i++) {
result += this.item[i] + ' ';
}
return result;
}
}
2眨补、隊列結構
1、一般隊列
特點: 先進先出
Js代碼實現:
class Queue {
constructor() {
this.item = [];
}
enqueue(val) {
this.item.push(val);
}
dequeue() {
return this.item.shift();
}
front() {
return this.item[0];
}
isEmpty() {
return this.item == 0;
}
size() {
return this.item.length;
}
toString() {
let result = '';
for (let i = 0; i < this.item.length; i++) {
result += this.item[i] + ' ';
}
return result;
}
}
2倒脓、優(yōu)先級隊列
特點: 數據優(yōu)先級越高撑螺,越先出來
JS代碼實現:
class PriorityQueue extends Queue {
constructor(element, priority) {
super();
this.element = element;
this.priority = priority;
}
enqueue(element, priority) {
const qe = new PriorityQueue(element, priority);
let isAdd = false;
if (this.item.length == 0) {
this.item.push(qe);
isAdd = true;
} else {
for (let i = 0; i < this.item.length; i++) {
if (qe.priority < this.item[i].priority) {
this.item.splice(i, 0, qe);
isAdd = true;
break;
}
}
if (!isAdd) {
this.item.push(qe);
}
}
}
toString() {
let result = '';
for (let i = 0; i < this.item.length; i++) {
result += this.item[i].element + ' ';
}
return result;
}
}