小弟数据结构在看
看到一个地方有点不明白 是关于使用栈来查找有续表的问题。我不明白什么叫使用栈来迭代 哪位大哥可以帮帮我解释一下 下面的代码到底跟栈有什么关系 为什么需要用栈来实现迭代?
什么叫栈的迭代版本?
private class Record
{
private int first, last;
private Record(int firstIndex, int lastIndex)
{
first = firstIndex;
last = lastIndex;
} // end constructor
} // end Record
private boolean binarySearch(int first, int last, T desiredItem)
{
StackInterface<Record> programStack = new LinkedStack<Record>();
boolean found = false;
boolean done = false;
programStack.push(new Record(first, last));
while (!done && !programStack.isEmpty())
{
Record topRecord = programStack.pop();
first = topRecord.first;
last = topRecord.last;
int mid = (first + last)/2;
if (first > last)
{
found = false;
done = true;
}
else if (desiredItem.equals(list[mid]))
{
found = true;
done = true;
}
else
{
if (desiredItem.compareTo(list[mid]) < 0)
programStack.push(new Record(first, mid - 1));
else
programStack.push(new Record(mid + 1, last));
} // end if
} // end while
return found;
} // end binarySearch
看到一个地方有点不明白 是关于使用栈来查找有续表的问题。我不明白什么叫使用栈来迭代 哪位大哥可以帮帮我解释一下 下面的代码到底跟栈有什么关系 为什么需要用栈来实现迭代?
什么叫栈的迭代版本?
private class Record
{
private int first, last;
private Record(int firstIndex, int lastIndex)
{
first = firstIndex;
last = lastIndex;
} // end constructor
} // end Record
private boolean binarySearch(int first, int last, T desiredItem)
{
StackInterface<Record> programStack = new LinkedStack<Record>();
boolean found = false;
boolean done = false;
programStack.push(new Record(first, last));
while (!done && !programStack.isEmpty())
{
Record topRecord = programStack.pop();
first = topRecord.first;
last = topRecord.last;
int mid = (first + last)/2;
if (first > last)
{
found = false;
done = true;
}
else if (desiredItem.equals(list[mid]))
{
found = true;
done = true;
}
else
{
if (desiredItem.compareTo(list[mid]) < 0)
programStack.push(new Record(first, mid - 1));
else
programStack.push(new Record(mid + 1, last));
} // end if
} // end while
return found;
} // end binarySearch
使用栈,也许是为了描述和C语言的迭代类似的原理。
误人子弟