因此,我正在尝试使用链表编写一个方法,称为
public void insert(Task t)
我不太确定如何编写该方法,但我知道如何编写一个类似的方法,称为
public void insert(int index, int value)
它看起来像这样:
public void insert(int index, int value) throws ListException {
int i = 0;
if (index > getLength()) {
throw new ListException("Index beyond bounds");
}
IntegerListNode prev = null;
IntegerListNode curr = head;
while (curr != null) {
if (index > i) {
i++;
prev = curr;
curr = curr.next;
} else {
break;
}
}
IntegerListNode newNode = new IntegerListNode(value);
newNode.next = curr;
if (prev == null) {
head = newNode;
} else {
prev.next = newNode;
}
System.out.println(this);
}
此方法的作用是在链表中的指定索引处插入一个值。我应该做的是编写一个类似的方法,但是我应该使用一个名为task的类,而不是使用整数对象。下面是这个类的样子。
public class Task {
int priority;
int number;
Task(int priority, int number) {
this.priority = priority;
this.number = number;
}
}
那么我应该如何调用这个方法,我应该在这个方法中放入什么呢?
编辑:这是我写的tasklistnode:
class TaskListNode {
int priority;
int number;
TaskListNode next;
TaskListNode(int priority, int number) {
this.priority = priority;
this.number = number;
this.next = null;
}
}
发布于 2015-02-19 08:17:27
免责声明:虽然有些信息似乎丢失了,但有时写得很好的代码(命名合理的变量、方法和类)可以作为很好的文档。在此基础上,我得出了一些结论。
给定的:
priority
.ListException
的随机insert
.Task
的链表实现在提供index
时引发,但在提供Task
时不引发。可能的用例:
任务的优先级列表(存储在按priority
排序的链表中的Task
对象)。
解决方案:
IntegerListNode
的类TaskListNode
。它应该接受constructor.
public void insert(Task t)
方法中的Task
,就像您编写的方法一样。因为索引不是专门提供的,所以它不能抛出ListException
__.
No index
=> No ListException
__.
Task
)遍历链表,直到找到比指定Task
更低的优先级为止。高优先级Task
__s应该在列表的前面。
希望这能有所帮助。
祝好运。
https://stackoverflow.com/questions/28594758
复制相似问题