Frage

How do you supposed to remove n numbers of element from a linked list?

for example.. given the start, and end index 2, 4.

my list contains:

1, 4, 6, 7, 8, 4

after the call,(6,7,8 should be gone) my list contains:

1, 4, 4

Ok, now i know how to remove an element at a given index. But i still dont know how to remove more than one elements.

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;
}
War es hilfreich?

Lösung

Spot the node before the starting index (let's call it firstNode) and the node in the ending index (let's call it lastNode), then just link firstNode to lastNode and let the other nodes free. Don't worry about memory leaks, the GC will notice the isolation island and will remove them from memory.

In pseudocode (since it's your homework to implement it):

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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top