【问题标题】:Use a constructor to copy a Stack使用构造函数复制堆栈
【发布时间】: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 作为它的构造函数,我该如何处理节点?创建一个新的类节点??有人能帮帮我吗:)

【问题讨论】:

  • 您注意到NodeStack 中的私有类。您只需将复制构造函数添加到它。
  • 你是什么意思“创建一个新的类节点”?你已经有一个Node 类,所以只需向它添加新的节点复制构造函数(并添加无参数构造函数,因为你不会再免费获得它了)。
  • 你可能会去克隆,深拷贝
  • 是的,正如 Andreas 所说,我已经在内部类中构建了一个构造函数。

标签: java data-structures constructor stack


【解决方案1】:

您不需要创建新的类节点。旧堆栈和新堆栈“t”的节点相同。

目前,您的Stackpublic Stack() 中有一个构造函数。您需要创建另一个接受堆栈的堆栈,就像您在示例中所做的那样,然后调用一个将旧元素复制到新堆栈的方法(递归或迭代)。这听起来像是家庭作业,所以我认为任何代码都不合适(不确定这方面的规则)。

【讨论】:

    【解决方案2】:

    这是我解决问题的代码片段

       private class Node{
        Item item;
        Node next;
        Node()    {  }                          //default constructor Node
        Node(Node x){
            item=x.item;
            if(x.next!=null) next=new Node(x.next);     
        }
    }
    public Stack(){                     //default constructor Stack
        first=null;
        N=0;        
    }
    
    public Stack(Stack<Item> s) {first=new Node(s.first); }
    

    【讨论】:

    • 这是不正确的!您正在尝试使用两个不同的头部引用同一个堆栈
    猜你喜欢
    • 1970-01-01
    • 2013-04-29
    • 1970-01-01
    • 2017-03-27
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 1970-01-01
    相关资源
    最近更新 更多