gpt4 book ai didi

java - 单链表 : Removing

转载 作者:行者123 更新时间:2023-12-01 13:29:57 28 4
gpt4 key购买 nike

尝试编写一种方法,从单链表中删除某个值的所有实例,但它似乎不起作用。

我试图适应头部是否包含该值,但我不确定这是否是正确的方法:

public void remove (int value)
{
if (head.value == value)
{
head = head.next;
count--;
}
IntegerNode temp=head;
while (temp !=null)
{
if (temp.next != null)
{
if (temp.next.value == value)
{
temp.next = temp.next.next;
count--;
}
}
temp=temp.next;
}
}

我的代码有明显的问题吗?

最佳答案

这里使用 addremove 方法实现链表并进行测试。

public class ListDemo {
public static void main(String[] args) {
MyList list = new MyList();
list.addToEnd(1);
list.addToEnd(2);
list.addToEnd(3);

list.removeByValue(2);
list.removeByValue(3);
}

}

class MyList {
private IntegerNode head;
private int count = 0;

public void addToEnd(int value) {

if(head == null) {
head = new IntegerNode(value);
count = 1;
head.next = null;
return;
}
IntegerNode current = head;
while (current.next != null) {
current = current.next;
}
IntegerNode node = new IntegerNode(value);
node.next = null;

count++;
current.next = node;
}

public void removeByValue(int value) {
if (count == 0) {
return;
} else if (count == 1) {
if (head.value == value) {
count = 0;
head = null;
}

} else {
IntegerNode current = this.head;
IntegerNode next = current.next;
while (next != null) {
if (next.value == value) {
if (next.next == null) {
current.next = null;
count--;
return;
} else {
current.next = next.next;
count--;
}
}
next = next.next;
}
}
}
}

class IntegerNode {
IntegerNode(int value) {
this.value = value;
}

IntegerNode next;
int value;
}

关于java - 单链表 : Removing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21627108/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com