假设我有一个链接列表。
class LinkedList {
...
private Node head;
private int length;
private class Node {
Element element;
Node next;
}
public LinkedList tail() { }
}
我将如何实现tail
以便:
- 它返回
LinkedList
,不带Head
元素。 - 对原始
LinkedList
所做的任何更改都会反射(reflect)在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
。
最佳答案
创建一个包含原始 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 变成一个接口(interface),将当前的 LinkedList 变成 LinkedListImplimplements LinkedList 并添加如上所述的 TailList。
class LinkedListImpl implements LinkedList{
...
LinkedList tail(){ return new TailList(this); }
...
}
顺便说一句。我建议考虑不可变的数据结构......
关于java - 返回类的副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28316714/