java使用构造函数复制堆栈
最近,我在学习算法,当我来解决
Create a new constructor for the linked-list implementation of Stack.java so that Stack t = new Stack(s) makes t reference a new and independent copy of the stack s.
这是堆栈。java
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Stack<Item> implements Iterable<Item> {
private Node<Item> first; // top of stack
private int n; // size of the stack
private static class Node<Item> {
private Item item;
private Node<Item> next;
}
/**
* Initializes an empty stack.
*/
public Stack() {
first = null;
n = 0;
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return n;
}
public void push(Item item) {
Node<Item> oldfirst = first;
first = new Node<Item>();
first.item = item;
first.next = oldfirst;
n++;
}
public Item pop() {
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
Item item = first.item; // save item to return
first = first.next; // delete first node
n--;
return item; // return the saved item
}
private class ListIterator<Item> implements Iterator<Item> {
private Node<Item> current;
public ListIterator(Node<Item> first) {
current = first;
}
public boolean hasNext() {
return current != null;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
}
The answer of Recursive solution is that create a copy constructor for a linked list starting at a given Node and use this to create the new stack.
Node(Node x) {
item = x.item;
if (x.next != null) next = new Node(x.next);
}
public Stack(Stack<Item> s) { first = new Node(s.first); }
但让我困惑的是如何将上述代码组合到堆栈中。java作为其构造函数,如何处理节点?要创建新的类节点??也许有人能帮我:)
# 1 楼答案
您不需要创建新的类节点。旧堆栈和新堆栈“t”的节点相同
当前
Stack
类public Stack()
中有一个构造函数。您需要创建另一个接受堆栈的方法,就像您在示例中所做的那样,然后调用一个方法将旧元素复制到新堆栈(递归或迭代)。这听起来像是家庭作业,所以我认为任何代码都不合适(不确定这方面的规则)# 2 楼答案
这是我解决问题的代码片段