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