返回课程副本

时间:2015-02-04 08:27:03

标签: java oop linked-list return

假设我有一个链表。

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返回
  3. 我尝试过的事情:

      // 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

1 个答案:

答案 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); }
  ...
}

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