java - LinkedList 删除:为什么我们不用以前的覆盖头部?
问题描述
查看我的数据结构,了解一些新的工作面试要求。所以我有一个链接列表的删除方法。
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;
为什么我们不用 ? 覆盖head
(在本例中表示为first
)previous
?或者会是错误的逻辑吗?喜欢
// just bypass it
previous.next = current.next;
first=previous;
我的意思是previous
并且current
只是迭代列表的指针。而删除后的真实数据位于first
右边?抱歉,如果这样想会很奇怪。有时我奇怪的直觉只是在学习算法时出现,主要是因为我有点弱
解决方案
这样做会导致您的链表丢失前一个节点之前的所有节点。如果您有一个包含以下值的链表:
[1, 2, 3, 4, 5, 6, 7, 8]
你打电话delete(7)
,你的头会指向6
,你会有一个链表[6, 8]
。