【发布时间】:2016-05-18 18:57:40
【问题描述】:
给定一个循环链表,用Java编写一个删除节点的方法。
【问题讨论】:
-
欢迎来到 StackOverflow!我们不为您编写代码!我们很想帮助你,但如果你不努力,我们也不会。
-
我正在做一个问答的事情,因为我没有找到我要找的东西。显然我做得不对。
标签: java linked-list circular-list
给定一个循环链表,用Java编写一个删除节点的方法。
【问题讨论】:
标签: java linked-list circular-list
实际上有四种情况需要考虑。
案例 1:
列表是空的吗?如果是,则返回 null 或返回
案例 2:
列表中只有一个元素。 将指针设置为 null,将列表设置为 null。
案例 3:
删除列表前面的内容。 在这种情况下,我们有几个步骤。
步骤:
案例 4:
删除这种格式的东西 1->2->3-> 我们正在删除中间的项目。 注意。这也适用于删除最后一项,因为它会循环回到 1。
步骤
将删除节点的指针设置为空。
public void delete(int data) {
// Null list case
if(list == null) return;
// Delete the only element case
if(list.data == data && list.next.data == list.data) {
list.next = null;
list = null;
return;
}
// Delete the front of the list case
if(list.data == data) {
// Move to the end of the list
Node end = list;
while(end.next.data != list.data) {
end = end.next;
}
Node temp = list;
list = list.next;
temp.next = null;
end.next = list;
return;
}
// Delete something in the middle
Node temp = list;
while(temp.next.data != data && temp.next.data != list.data) {
temp = temp.next;
}
// We circled the list and did not find the element to delete
if(temp.next.data == list.data) return;
Node del = temp.next;
temp.next = temp.next.next;
del.next = null;
}
【讨论】:
Node 的方法,但在此方法中,您提供了删除内容与int 匹配的节点的方法。这也假设循环链表中只有唯一元素。