亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我的代碼有什么問題,我正在嘗試使用內部和外部方法在堆棧中搜索

我的代碼有什么問題,我正在嘗試使用內部和外部方法在堆棧中搜索

慕容3067478 2021-11-17 10:31:54
編寫一個方法來查找給定元素在堆棧中的位置,從堆棧頂部開始計數。更準確地說,如果元素出現在頂部,該方法應該返回 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


查看完整回答
反對 回復 2021-11-17
  • 1 回答
  • 0 關注
  • 130 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號