LinkedList实现方式:
因为js没有LinkedList,以下是自己实现的LinkedList:
function LinkedList() {
var Node = function(element) {
this.element = element;
this.next = null;
}
var length = 0;
var head = null;
this.add = function(element) {
var node = new Node(element),current;
if (head==null) {
head = node;
} else {
current = head;
while(current.next) {
current = current.next;
}
current.next = node;
}
length++;
}
this.set = function(index, element) {
var a = this.get(index);
a = element;
}
// 删除最顶端元素
this.remove = function() {
if (this.isEmpty()) {
return undefined;
}
var h = head.element;
head = head.next;
length --;
return h;
}
this.isEmpty = function() {
return length == 0;
}
this.get = function(index) {
var num = 0, current;
if (index < 0) throw new RangeError("Index out of range");
current = head;
while(num++ < index) {
current = current.next;
}
var a = current.element;
return a;
}
}
module.exports = LinkedList;以下是自己实现的队列queue类:
function Queue() {
var queue = {};
var count = 0;
var lowCount = 0;
// 入队
this.add = function(value) {
queue[count++] = value;
}
// 出队
this.remove = function() {
if (this.isEmpty()) {
return undefined;
}
var result = queue[lowCount];
delete queue[lowCount];
lowCount++;
return result;
}
this.isEmpty = function() {
return this.size() == 0;
}
this.peek = function() {
if (this.isEmpty()) {
return null;
}
return queue[lowCount];
}
this.clear = function() {
count = 0;
lowCount = 0;
queue = {};
}
this.size = function() {
return count - lowCount;
}
}
module.exports = Queue;以下是图的广度优先遍历方式:
const LinkedList = require("../util/LinkedList");
const Queue = require("../util/Queue");
const Graph = require("../graph/Graph");
function GraphBFS($g) {
var G = $g, visited = new Array(G.V()).fill(false), queue = new LinkedList(), order = [];
var bfs = function ($v) {
visited[$v] = true;
queue.add($v);
while (!queue.isEmpty()) {
var v = queue.remove();
order.push(v);
for (var w of G.adj(v)) {
if (!visited[w]) {
queue.add(w);
visited[w] = true;
}
}
}
}
for (var v = 0; v < G.V(); v++) {
if (!visited[v]) {
bfs(v);
}
}
this.order=function () {
return order;
}
}
var g = new Graph('data/图的BFS实现/g.txt');
var graphBFS = new GraphBFS(g);
console.log('图的广度优先遍历结果:', graphBFS.order())上面GraphBFS中的queue不管是实现的Queue还是LinkedList都能实现图的广度优先遍历。从代码上看Queue的性能是优于LinkedList的,不知道老师为何在实现这个queue采用的是链表呢?还是因为JAVA中关于LinkedList是跟我这里是有本质区别的?