const findFirstNode = (nodeList) => {
const ids = nodeList.map(item => item.id);
const nextIds = nodeList.map(item => item.nextId);
let headNo = [];
for (var i = 0; i < nextIds.length; i++) {
console.log('nextIds', nextIds[i]);
if (!ids.includes(nextIds[i])) {
headNo.push(nextIds[i]);
}
}
if (!headNo.length) {
throw Error('该链表是环状');
}
if (headNo.length > 1) {
throw Error('存在节点不在链表内');
}
return headNo[0];
}
const list = [{ "id": 3, "nextId": 0 }, { "id": 1, "nextId": 2 }, { "id": 2, "nextId": 3 }];
console.log(findFirstNode(list));