i have a very simple code here which uses recursion to iterate the queue class i need to simple print 6 on screen but it print 1 ,please tell me where i am wrong.
protected void Button1_Click(object sender, EventArgs e)
{
q.Enqueue(1);
q.Enqueue(2);
q.Enqueue(3);
q.Enqueue(4);
q.Enqueue(5);
q.Enqueue(6);
long id = ge开发者_运维百科tID(Convert.ToInt64(q.Dequeue()));
Response.Write(id);
}
private long getID(long id)
{
if (id == 6)
{
return id;
}
else
{
id = Convert.ToInt64(q.Dequeue());
if (q.Count != 0)
{
getID(id);
}
else
{
}
}
return id;
}
}
You are missing a return:
if (q.Count != 0)
{
return getID(id); // Here
}
Currently your code calls getID
but simply discards the result. Then when control reaches the end of the method it returns id
.
Replace
if (q.Count != 0)
{
getID(id);
}
with
if (q.Count != 0)
{
return getID(id);
}
You're not doing anything with the return value of the recursive call, so your top-level getID
will simply return its parameter when it hits the bottom.
Try return getID(id)
in the if
test.
精彩评论