Let's say I have a linked list.
class LinkedList {
...
private Node head;
private int length;
private class Node {
Element element;
Node next;
}
public LinkedList tail() { }
}
How would I implement tail
so that:
LinkedList
, without the Head
element.LinkedList
is reflected upon what tail
returnsThings I've tried:
// 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;
}
Basically, I need tail
to point at the head.next
.
Create a subclass of LinkedList which wraps the original:
class TailList extends LinkedList {
LinkedList list;
TailList(LinkedList list) { this.list=list;}
Node head() { return list.head().next; }
int length() { return list.length()-1;}
}
Of course you have to encapsulate the fields in LinkedList first. I would actually turn LinkedList into an interface, turn your current LinkedList into LinkedListImpl implements LinkedList and add the TailList as described above.
class LinkedListImpl implements LinkedList{
...
LinkedList tail(){ return new TailList(this); }
...
}
Btw. I recommend considering immutable data structures...
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments