# 210. 课程表 II（JS实现）

## 3代码

``````/** * @param {number} numCourses * @param {number[][]} prerequisites * @return {number[]} */
var findOrder = function(numCourses, prerequisites) {

const res = [];

if (prerequisites.length === 0) {
for (let i=0; i<numCourses; i++) {
res.push(i);
}
return res;
}

const vexs = [];

for (let arr of prerequisites) {
if (!vexs[arr[0]]) {
vexs[arr[0]] = new Node(arr[0]);
}

if (!vexs[arr[1]]) {
vexs[arr[1]] = new Node(arr[1]);
}

let firstEdge = vexs[arr[1]].firstEdge;
vexs[arr[1]].firstEdge = { vex: vexs[arr[0]], next: firstEdge};
vexs[arr[0]].in++;
}

const stack = [];

for (let i=0; i<numCourses; i++) {
if (vexs[i]) {
if (vexs[i].in === 0) stack.push(vexs[i]);
} else {
res.push(i);     // 保存没有任何边连接的节点
}
}

while(stack.length > 0) {
let currentVex = stack.pop();
res.push(currentVex.val);    //保存节点
let currentEdge = currentVex.firstEdge;
while(currentEdge) {
if (--currentEdge.vex.in === 0) {
stack.push(currentEdge.vex);
}
currentEdge = currentEdge.next;
}
}

return res.length < numCourses ? [] : res;
};

function Node(val) {
this.val = val;
this.firstEdge = null;
this.in = 0;
}
``````
原文作者：PAT-python-zjw
原文地址: https://blog.csdn.net/zjw_python/article/details/107891891
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。