好的,我必须创建一个程序来确定if a Stack of CalendarDates is sorted or not.
该参数正在使用堆栈:
CalendarDate[] store = {new CalendarDate(1,2), new CalendarDate(1,1), new CalendarDate(12,30)};
So it will return false as (1,1) comes after (1,2).
无论如何,这是我的代码:
public static boolean isSorted(Stack<CalendarDate> c){
Queue<CalendarDate> q = new LinkedList<CalendarDate>();
CalendarDate peek = c.peek();
while (!c.empty()){
CalendarDate peeker = c.peek();
if (peeker.compareTo(peek)>0){
return false;
}
else{
q.add(c.pop());
peek=peeker;
}
}
while (!q.isEmpty()){
c.push(q.remove());
}
while(!c.empty()){
q.add(c.pop());
}
while(!q.isEmpty()){
c.push(q.remove());
}
return true;
}
我得到的唯一错误是在我说CalendarDate peek的第3行 = c.peek();这是一个“空洞的例外”
为什么我收到此错误?
答案 0 :(得分:0)
由于Stack
是List
的后代,你可以在不使用pop / push / peek的情况下编写你的算法,只需使用迭代器迭代堆栈(这是一个列表):
public static boolean isSorted(Stack<CalendarDate> c){
Iterator<CalendarDate> it = c.iterator();
CalendarDate lastItem = null;
while( it.hasNext() ){
CalendarDate currentItem = it.next();
if( lastItem != null && lastItem.compareTo( currentItem ) > 0 ){
return false;
}
lastItem = currentItem;
}
return true;
}