如何将自定义链表转换为数组?
我必须实现一个方法:
E[] toArray(E[] a) // Pass an array, convert to singly linked list, then return the array.
来自 java.util
Interface List
正如我提到的,我必须传递一个数组,将其转换为单链表,排序它,然后返回数组。
在 Node
类中,我需要处理这个问题:
public Node(E v, Node<E> next) {
// pre: v is a value, next is a reference to remainder of list
// post: an element is constructed as the new head of list
data = v;
nextElement = next;
}
public Node(E v) {
// post: constructs a new tail of a list with value v
this(v,null);
}
public Node<E> next() {
// post: returns reference to next value in list
return nextElement;
}
public void setNext(Node<E> next) {
// post: sets reference to new next value
nextElement = next;
}
public E value() {
// post: returns value associated with this element
return data;
}
public void setValue(E value) {
// post: sets value associated with this element
data = value;
}
我是不是找错了树,或者有人可以帮我解决这个问题吗?很抱歉,如果这是提出此类问题的错误地方。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下代码将创建单个链接列表并将其复制回数组的新副本。对于这种排序,您需要确保使“E”类型实现具有可比性。>。
一种方法是将“E”的通用声明符更改为
The following code will create the single linked list and copy that back to new copy of the array. For the sort you need to make sure you make the \"E"\ type implementes comparable.
One way is to change the generic declarator of \"E"\, to <E extends Comparable<? super E>>.
明显的错误答案:
我认为构建和排序您完全跳过的链表有一些副作用?或者也许返回应该是排序列表,而不是数组,可能是排序列表强制回数组?
Obvious wrong answer:
I assume there are some side effect to constructing and sorting the linked list that you completely skipped? Or maybe the return is supposed to be the sorted list, not the array, possibly the sorted list coerced back into an array?
我希望这能满足您的需求:
正如我在代码中所说,我不知道如何正确实例化泛型类。有人可以纠正我吗?
I hope this does what you want:
As I say in the code, I don't know how to correctly instantiate a generic class. Can someone correct me?