【发布时间】:2017-07-13 06:09:12
【问题描述】:
我有一个问题,我必须在堆栈中搜索最大元素。我创建了自己的堆栈类并使用了以下方法:
Node node = top; //created a new node which points to the top of stack
int max = node.data; //max contains the value of the top node
while(node != null) {
if(node.data > max) {
max = node.data;
}
node = node.next;
}
//Print the value of max.
谁能提出一个更有效的方法来做到这一点?
【问题讨论】:
-
除非您的堆栈以某种方式排序,否则没有比 O(n) 更快的方法!?您可以使用多线程解决方案,但可能就是这样。
标签: java search data-structures stack