【发布时间】:2016-08-04 14:40:40
【问题描述】:
最近我在学习算法4次,当我来解决这个问题时
为 Stack.java 的链表实现创建一个新的构造函数,以便 Stack t = new Stack(s) 使 t 引用堆栈 s 的一个新的独立副本。
这里是 Stack.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;
}
}
递归解决方案的答案是,为从给定节点开始的链表创建一个复制构造函数,并使用它来创建新堆栈。
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); }
但是让我困惑的是如何将上面的代码组合到 Stack.java 作为它的构造函数,我该如何处理节点?创建一个新的类节点??有人能帮帮我吗:)
【问题讨论】:
-
您注意到
Node是Stack中的私有类。您只需将复制构造函数添加到它。 -
你是什么意思“创建一个新的类节点”?你已经有一个
Node类,所以只需向它添加新的节点复制构造函数(并添加无参数构造函数,因为你不会再免费获得它了)。 -
你可能会去克隆,深拷贝
-
是的,正如 Andreas 所说,我已经在内部类中构建了一个构造函数。
标签: java data-structures constructor stack