java - 从链表中删除n个元素(这里处理节点)

标签 java linked-list nodes

如何从链表中删除 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/

相关文章:

java - net.sf.json.JSONObject 在不需要的地方添加反斜杠?

java - Sikuli:无论模式是否存在,onAppear 都会起作用

java - 检查节点是否有完全连接的邻居

java eclipse 插件 : menuitems appear in windows but not on linux

java - 尝试使用 struts-jquery-tags 但遇到多个异常?

c - 用于基数排序的链表中的指针上的 EXC_BAD_ACCESS

c - 如何解决链表中损坏的指针?

c++ - 在cpp LinkedList程序中将两个多项式相乘

algorithm - 如果在减少相邻节点值后没有一个减少到 0,在拓扑排序中该怎么办?

python - 如何在 python 中创建 Drop-Out Stack?