gpt4 book ai didi

java - 不使用 "clone"复制堆栈或队列

转载 作者:行者123 更新时间:2023-12-02 09:40:04 27 4
gpt4 key购买 nike

不使用克隆复制堆栈和队列。例如,当我调用传递堆栈的方法时,我无法修改保留传递的原始堆栈。我需要复制/克隆传递的堆栈以在方法中更改/使用。

我只能使用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();
}

}

我的解决方案

public static Stack<CalendarDate> sToS(Stack<CalendarDate> orgin) {
// Create a temp stack
Stack<CalendarDate> temp = new Stack<CalendarDate>();

// 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<CalendarDate> copy = new Stack<CalendarDate>();

// 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;
}

最佳答案

想象一个场景,您有三个堆栈:堆栈 A(要从中复制的堆栈)、堆栈 B(要复制到的目标)和堆栈临时(辅助堆栈)。

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

充分理解的最好方法是举个例子并亲自尝试一下。或者您可以简单地在编码平台上搜索方法,例如 GeeksForGeeks

关于java - 不使用 "clone"复制堆栈或队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57150551/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com