[英]Java NODE of singly-linked list
我把最后的任务发给我的老师,他说
extract function
仅在现有节点上运行; 没有创建新节点!
我的摘录function 是:
public static Node[] extract(Node head) {
Node oddNum = null;
Node x = null;
Node even = null;
Node y = null;
Node[] a = new Node[2];
while (head != null){
if ((head.data & 1) != 0) {
if (oddNum == null) {
oddNum = head;
x = head;
}
else {
x.next = head;
x = x.next;
}
}
else {
if (even == null) {
even = head;
}
else {
y.next = head;
}
y = head;
}
head = head.next;
}
a[0] = even;
a[1] = oddNum;
return a;
}
而我的主要class 包含
int[] tab = { 2, 1, 4, 3, 6, 5, 7, 8 };
Node head = arrayToList(tab);
showList(head);
Node[] nodes = extract(head);
System.out.println();
showList(nodes[0]);
System.out.println();
showList(nodes[1]);
where 方法arrayToList创建包含数组中整数的节点列表并返回此列表的头部。
Function extract引用列表的头部。 function 将列表分成两部分——一个只包含偶数数据的节点,另一个包含奇数数据的节点。 返回这些列表的头部的二元素数组。
问题是:我应该如何修复提取 function? 我真的不知道,因为我的摘录 function 包含新节点 Node[] a = new Node[2];
提前致谢!
您的extract()
方法不会返回新的Node
实例,而是从现有链中返回Node
实例。 此外,您的方法是通过从现有Node
实例更改x.next
和y.next
来更改提供的Node
链,这会导致破坏原始提供的Node
链。
您的方法必须为偶数和奇数返回两个新的Node
链,而不是更改/更改提供的Node
链。 遍历给定的Node
链,并相应地将新的Node
实例添加到“偶数”或“奇数”链中。 然后返回这两个新的Node
链。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.