如何从链表中删除 n 个元素?
例如..给定开始和结束索引 2, 4。
我的列表包含:
1, 4, 6, 7, 8, 4
通话结束后,(6,7,8 应该消失)我的列表包含:
1, 4, 4
好的,现在我知道如何删除给定索引处的元素。但我仍然不知道如何删除多个元素。
if(index == 0) {
front = front.next;
} else {
ListNode current = front;
for (int i = 0; i < index - 1; i++) {
current = current.next;
}
current.next = current.next.next;
}
最佳答案
找到起始索引之前的节点(我们称之为firstNode)和结束索引中的节点(我们称之为lastNode),然后将firstNode链接到lastNode并让其他节点空闲。不用担心内存泄漏,GC 会注意到隔离岛并将其从内存中删除。
用伪代码(因为实现它是你的作业):
function removeNodes (int startIndex, int endIndex)
if startIndex > endIndex or startIndex < 0 then
exit function
end if
Node firstNode, lastNode
firstNode <- head
int currentIndex = 0
while currentIndex < startIndex
firstNode <- firstNode->next
currentIndex <- currentIndex + 1
end while
lastNode <- firstNode->next
currentIndex <- currentIndex + 1
while lastNode is not null and currentIndex <= endIndex
lastNode <- lastNode->next
currentIndex <- currentIndex + 1
end while
if lastNode is not null
firstNode->next = lastNode->next
else
firstNode->next = null
end if
//if you happen to have a size field for your LinkedList class,
//update it as needed...
end function
关于java - 从链表中删除n个元素(这里处理节点),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22216557/