q = collections.deque() # 初始化队列,入度为0的进入队列 for i inrange(n): if in_nums[i] == 0: q.appendleft(i) ans = [] while q: cur_node = q.pop() ans.append(cur_node) # 拿走一个节点后,需要删除这个节点指向其他节点的边 for x in graph[cur_node]: in_nums[x] -= 1 if in_nums[x] == 0: q.appendleft(x) return ans