这是问题陈述,
你有很多带有出发地和目的地的门票。您获得了出发城市和目的地城市。你怎么能从堆栈中找到你的路线。 这是我的解决方案,
"use strict";
function app(){
var stack = [];
var one = new Ticket('London', 'NYC');
var two = new Ticket('Barcelona', 'Athens');
var three = new Ticket('Rio', 'ND');
var four = new Ticket('NYC', 'Barcelona');
var five = new Ticket('Athens', 'Rio');
var six = new Ticket('ND', "Lahore");
stack.push(one);
stack.push(two);
stack.push(three);
stack.push(four);
stack.push(five);
stack.push(six);
var res = sortDestinations(stack, 'London', 'Lahore');
for(var city in res){
console.out(res[city]);
}
}
function Ticket(departure, destination){
this.departure = departure;
this.destination = destination;
}
Ticket.prototype.getDeparture = function(){
return this.departure;
}
Ticket.prototype.getDestination = function(){
return this.destination;
}
function sortDestinations(stack, dep, dest){
var map = {};
for(var i= 0; i<stack.length; i++){
var ticket = stack.pop();
map[ticket.getDeparture()] = ticket.getDestination();
}
var res = [];
var curr = dep;
res.push(curr);
while(true){
if(curr == dest) {
break;
}
var next = map[curr];
res.push(next);
curr = next;
}
}
app();
这个程序进入无限循环。当我调试时,我看到curr变量未定义。有人可以帮我解决问题。我是Javascript的新手。
答案 0 :(得分:0)
我正在调试您的代码一段时间,最后确定了infinite loop
的原因。
由于pop
来自stack
,stack
的长度不断减少,i
的长度增加,循环在完成前停止。并且while
循环保持循环,因为curr
永远不会等于dept
,因为map
不包含London
。
更改此
for(var i= 0; i<stack.length; i++){
var ticket = stack.pop();
map[ticket.getDeparture()] = ticket.getDestination();
}
到
while(stack.length>0){
var ticket = stack.pop();
map[ticket.getDeparture()] = ticket.getDestination();
}