【发布时间】:2014-09-25 22:38:40
【问题描述】:
这个自定义类模仿了 Java 的 LinkedList 类的功能,只是它只接受整数并且显然缺少大部分功能。对于这个方法,removeAll(),我将遍历列表的每个节点并删除具有该值的所有节点。我的问题是,当列表中的第一个节点包含要删除的值时,它会忽略所有也包含该值的后续节点。似乎是什么问题?我是否以错误的方式删除了前端节点?例如,[1]->[1]->[1] 应该返回一个空列表,但它离开了前端节点,我得到 [1]
编辑:似乎无法删除第二个节点而不是第一个节点。
这是类(将 ListNodes 存储为列表):
public class LinkedIntList {
private ListNode front; // first value in the list
// post: constructs an empty list
public LinkedIntList() {
front = null;
}
// post: removes all occurrences of a particular value
public void removeAll(int value) {
ListNode current = front; // primes loop
if (current == null) { // If empty list
return;
}
if (front.data == value) { // If match on first elem
front = current.next;
current = current.next;
}
while (current.next != null) { // If next node exists
if (current.next.data == value) { // If match at next value
current.next = current.next.next;
} else { // If not a match
current = current.next; // increment to next
}
}
}
// post: appends the given value to the end of the list
public void add(int value) {
if (front == null) {
front = new ListNode(value);
} else {
ListNode current = front;
while (current.next != null) {
current = current.next;
}
current.next = new ListNode(value);
}
}
// Sets a particular index w/ a given value
public void set(int index, int value) {
ListNode current = front;
for (int i = 0; i < index; i++) {
current = current.next;
}
current.data = value;
}
}
这里是 ListNode 类(负责单个“节点”):
//ListNode is a class for storing a single node of a linked
//list. This node class is for a list of integer values.
public class ListNode {
public int data; // data stored in this node
public ListNode next; // link to next node in the list
// post: constructs a node with data 0 and null link
public ListNode() {
this(0, null);
}
// post: constructs a node with given data and null link
public ListNode(int data) {
this(data, null);
}
// post: constructs a node with given data and given link
public ListNode(int data, ListNode next) {
this.data = data;
this.next = next;
}
}
【问题讨论】:
-
您假设列表开头可能只有一个元素,等于删除的值。您应该使用循环
while (front.data == value){}而不是单个检查if (front.data == value) -
一个问题:如果列表只包含一个节点,并且该节点匹配,我如何删除该节点?我无法将其设置到另一个节点。
-
但您已经在当前程序中考虑过这种情况
标签: java linked-list nodes