gpt4 book ai didi

java - 链表删除 : why don't we override the head with previous?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:05:22 25 4
gpt4 key购买 nike

检查我的数据结构,了解一些新的面试要求。所以我有一个链表的删除方法。

public Link delete(int key) {
Link current = first;
Link previous = first;
while(current.iData != key) {
if(current.next == null)
return null;
else {
previous = current;
current = current.next;
}
}

if(current == first)
first = first.next;
else
// just bypass it
previous.next = current.next;
return current;
}

到目前为止,我想我明白了。但我对这条线很好奇。

// just bypass it
previous.next = current.next;

为什么我们不用 previous 覆盖 head(在本例中表示为 first)?或者会是错误的逻辑吗?喜欢

// just bypass it
previous.next = current.next;
first=previous;

我的意思是 previouscurrent 只是迭代列表的指针。而删除后的真实数据位于first对吧?抱歉,如果这样想为什么会很奇怪。有时我的奇怪直觉是在学习算法时出现的,主要是因为我有点虚弱

最佳答案

这样做会导致您的链表丢失前一个之前的所有节点。如果您有一个包含以下值的链表:

[1, 2, 3, 4, 5, 6, 7, 8]

然后你调用了delete(7),你的head会指向6,你会得到一个[6, 8]<的链表.

关于java - 链表删除 : why don't we override the head with previous?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58666225/

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