編寫一個方法來查找給定元素在堆棧中的位置,從堆棧頂部開始計數。更準確地說,如果元素出現在頂部,該方法應該返回 0,如果它上面有另一個元素,則返回 1,依此類推。如果元素出現多次,則應返回最上面的位置。如果元素根本沒有出現,則必須返回 -1。要求您以兩種不同的方式編寫此方法;一種方法是在 ArrayStack 類內部實現它,另一種方法是在單獨的類中外部實現它。重要提示:最后堆棧應返回到原始狀態(即不應刪除任何元素且不應更改元素的順序)。這是外部類public class Stack{public static int searchstack(ArrayStack z, int n) { ArrayStack temp = new ArrayStack(z.size()); int c = 0; boolean flag = false; while (!z.isEmpty()) { if (z.top() == n) { flag = true; return c; } if (z.top() != n) { temp.push(z.pop()); c++; flag = false; } } if (flag == false) { c = -1; } while (!temp.isEmpty() && !z.isFull()) { z.push(temp.pop()); } return c; } public static void main(String[] args) { ArrayStack z = new ArrayStack(4); z.push(3); // first element z.push(7);// 2nd z.push(8);// 3rd z.push(1);// 4th z.printStack(); int n = 3; System.out.println("Searching externally for" + " " + n + " " + searchstack(z, n)); System.out.println("Searching internally for" +" "+n+" "+ z.searchfor(n)+" "); //THE ERROR IS HERE} }這是 ArrayClasspublic class ArrayStack { private int[] theStack; private int maxSize; private int top;public ArrayStack(int s) { maxSize = s; theStack = new int[maxSize]; top = -1; }public void push(int elem) { top++; theStack[top] = elem; }public int pop() { int result = theStack[top]; top--; return result; }public int top() { return theStack[top]; }public boolean isFull() { return (top == (maxSize - 1)); }public boolean isEmpty() { return (top == -1); }Stack類出現的錯誤是在調用Arraystack類中實現的searchfor方法的最后一行,error表示Arraystack中沒有實現名為searchfor()的方法;雖然我確實實施了它。似乎是問題所在?
1 回答

ITMISS
TA貢獻1871條經驗 獲得超8個贊
您的 searchStack() 實現中有一個錯誤。如果您找到了您正在尋找的元素,并且它不是最頂層的元素,那么您就會丟失元素。
如何修復您的 searchStack() 方法:
繼續彈出 z 直到你有一個空的 ArrayStack。這樣做時,將該值添加到隊列中。
創建 valIndex 并將其分配給 -1。
然后遍歷隊列并從中刪除項目并將它們添加到 z。這樣做時,檢查所需值的最后一次出現并將其保存在 valIndex 中。
如果 valIndex 等于 -1,則返回它。否則,使用以下等式將其轉換為正確的索引并返回:
valIndex = (z.size - 1) - valIndex
添加回答
舉報
0/150
提交
取消