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

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

不使用“克隆”復制堆棧或隊列

不使用“克隆”復制堆?;蜿犃?/h1>
冉冉說 2023-04-13 10:49:28
在不使用克隆的情況下復制堆棧和隊列。例如,當我調用一個傳遞堆棧的方法時,我不能修改保留傳遞的原始堆棧。我需要復制/克隆傳遞的 Stack 以在方法中更改/使用。我只能使用 Stack.java(附件)。我創建了以下輔助方法:public static Stack<CalendarDate> qToS(Queue<CalendarDate> q) {    Stack<CalendarDate> s = new Stack<CalendarDate>();    while (!q.isEmpty()) {       CalendarDate n = q.remove();       s.push(n);    }    return s; // Return stack s}public static Queue<CalendarDate> sToQ(Stack<CalendarDate> s) {    Queue<CalendarDate> q = new LinkedList<CalendarDate>();    while (!s.empty()) {       CalendarDate n = s.pop();       q.add(n);    }    return q; // Return queue q}/*          Provided as a Stack Class alternative    Limits user to actual Stack methods    so Vector<E> is not available*/public class Stack<E> {    // avoid blanked import of java.util    private java.util.Stack<E> secret;    // default constructor    public Stack() {        secret = new java.util.Stack<E>();    }     // empty that collection    public void clear() {        secret.clear();    }    // should be order constant    public int size() {        return secret.size();    }    // simply have push call push from API    public E push(E a) {        secret.push(a);        return a;    }    // And, empty calls empty from API    public boolean empty() {        return secret.empty();    }    // And my pop() uses pop() form JAVA API    public E pop() {        return secret.pop();    }    // My peek uses their peek    public E peek() {        return secret.peek();    }    // Following are not basic Stack operations    // but needed to do some simple testing    // toString is probably not O(constant)    public String toString() {        return secret.toString();    }}
查看完整描述

2 回答

?
互換的青春

TA貢獻1797條經驗 獲得超6個贊

想象一下您有三個 Stack 的場景,Stack A(您要從中復制的那個)、Stack B(您要復制到的目標)和一個 Stack temp(輔助 Stack)。


Step 1: (The Initial Stack)


|1|? | |? | |

|2|? | |? | |

|3|? | |? | |


?A? ?TEMP? B


Step 2: (Move elements from Stack A to Temp Stack)


| |? | |? | |

|2|? | |? | |

|3|? |1|? | |


?A? ?TEMP? B


| |? | |? | |

| |? |2|? | |

|3|? |1|? | |


?A? ?TEMP? B


| |? |3|? | |

| |? |2|? | |

| |? |1|? | |


?A? ?TEMP? B


Step 3: (Move elements from Temp stack to Stack A & B)


| |? | |? | |

| |? |2|? | |

|3|? |1|? |3|


?A? ?TEMP? B


| |? | |? | |

|2|? | |? |2|

|3|? |1|? |3|


?A? ?TEMP? B


|1|? | |? |1|

|2|? | |? |2|

|3|? | |? |3|


?A? ?TEMP? B


充分理解的最好方法是舉個例子并親自嘗試一下。



查看完整回答
反對 回復 2023-04-13
?
翻過高山走不出你

TA貢獻1875條經驗 獲得超3個贊

要復制堆棧:

  • 創建temp堆棧

  • 使用和將所有值從origin堆棧移動到堆棧temppoppush

  • origin堆棧現在是空的,并且temp堆棧是倒置的

  • 創建copy堆棧

  • 將所有值從temp堆棧移動到兩者origincopy同時堆棧

  • origin返回到原始內容,并且copy堆棧具有相同的內容。


查看完整回答
反對 回復 2023-04-13
  • 2 回答
  • 0 關注
  • 156 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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