java 队列复制_java - 复制堆栈或队列,而无需使用“克隆” - 堆栈内存溢出
復制堆棧和隊列,而無需使用克隆。 例如,當我調用傳遞堆棧的方法時,我無法修改保留傳遞原始堆棧的權限。 我需要對傳遞的堆棧進行復制/克隆以更改/在方法中使用。
我只能使用Stack.java(附加)。 我創建了以下輔助方法:
public static Stack qToS(Queue q) {
Stack s = new Stack();
while (!q.isEmpty()) {
CalendarDate n = q.remove();
s.push(n);
}
return s; // Return stack s
}
public static Queue sToQ(Stack s) {
Queue q = new LinkedList();
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 is not available
*/
public class Stack {
// avoid blanked import of java.util
private java.util.Stack secret;
// default constructor
public Stack() {
secret = new java.util.Stack();
}
// 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();
}
}
我的解決方案
public static Stack sToS(Stack orgin) {
// Create a temp stack
Stack temp = new Stack();
// Move all values from origin
// stack to temp stack using pop and push
while (!orgin.empty()) {
CalendarDate n = orgin.pop();
temp.push(n); // push here for the same order
}
// Create a copy stack
Stack copy = new Stack();
// Move all values from temp stack to
// both origin and copy stacks at the same time
while (!temp.empty()) {
CalendarDate n = temp.pop();
copy.push(n); // push here for the same order
orgin.push(n);
}
return copy;
}
總結
以上是生活随笔為你收集整理的java 队列复制_java - 复制堆栈或队列,而无需使用“克隆” - 堆栈内存溢出的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Mac OS X移动到文件结尾的快捷键是
- 下一篇: java swing运行没反应_java