【问题标题】:Returning a copy of class返回类的副本
【发布时间】:2015-02-04 08:27:03
【问题描述】:

假设我有一个链表。

class LinkedList {
...
    private Node head;
    private int length;

    private class Node {
        Element element;
        Node next;
    }

    public LinkedList tail() { }
}

我将如何实现tail 以便:

  1. 它返回 LinkedList,不带 Head 元素。
  2. 对原始 LinkedList 所做的任何更改都会反映在 tail 返回的内容上

我尝试过的事情:

  // This fails because it creates a new LinkedList, and modifying 'this' won't affect the new LinkedList.
  public LinkedList tail() {
    LinkedList temp = new LinkedList();
    temp.head = this.head.next;
    temp.length = this.length - 1;
    return temp;
  }

  // This fails because it modifies the original LinkedList.
  public LinkedList tail() {
    LinkedList temp = this;
    temp.head = this.head.next;
    temp.length = this.length - 1;
    return temp;
  }

基本上,我需要tail 指向head.next

【问题讨论】:

  • 我认为最简单的解决方案是使用 cons 列表而不是链表。
  • @BoristheSpider,嗯?
  • 链接列表不适合您的要求,因为您必须返回具有不同 head 元素的类的 new 实例 - 您的第一种方法。一个 cons 列表是一个持久的数据结构(来自函数式编程),正是为此用例设计的。
  • 您能否进一步解释一下为什么您的两个解决方案都失败了?您说第一个失败是因为修改“this”(即原始 LinkedList)不会影响返回的列表。您说第二个失败是因为修改原始 LinkedList (即“this”)确实会影响返回的列表。我可以明白为什么第二个显然不起作用,但我仍然不确定为什么第一个会失败?
  • 假设我有:list1 = new LinkedList();list2 = list1.tail()。在list1 的末尾添加一个元素应该会影响list2。但是在list1 前面添加一个元素应该不会影响list2

标签: java oop linked-list return


【解决方案1】:

创建一个包装原始的 LinkedList 的子类:

class TailList extends LinkedList {
  LinkedList list;
  TailList(LinkedList list) { this.list=list;}
  Node head() { return list.head().next; }
  int length() { return list.length()-1;}
}

当然你得先把LinkedList中的字段封装起来。我实际上会将 LinkedList 变成一个接口,将您当前的 LinkedList 变成 LinkedListImpl implements LinkedList 并如上所述添加 TailList。

class LinkedListImpl implements LinkedList{
  ...
  LinkedList tail(){ return new TailList(this); }
  ...
}

顺便说一句。我建议考虑不可变数据结构...

【讨论】:

  • 嗨,这将如何与tail 函数一起使用?我会返回TailList 还是LinkedList?在tail 内部:我要创建new TailList(this) 吗? TailList 是它自己的一个类,还是属于 LinkedList 内部?
  • 更新了答案。我会将 TailList 保留为链表实现的私有内部类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多