假设我有一个链表。
class LinkedList {
...
private Node head;
private int length;
private class Node {
Element element;
Node next;
}
public LinkedList tail() { }
}
我如何实施tail
以便:
LinkedList
,不包含Head
元素。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
。
答案 0 :(得分: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实现LinkedList 并添加TailList,如上所述。
class LinkedListImpl implements LinkedList{
...
LinkedList tail(){ return new TailList(this); }
...
}
顺便说一下。我建议考虑不可变数据结构...