Home > OS >  Im not sure why this code works I understand everything except for the line self._first = self._firs
Im not sure why this code works I understand everything except for the line self._first = self._firs

Time:01-18

I have a working program that removes the first element of a linked list. I'm not sure why the line self._first = self._first.next removes the first element of the list. Can someone please clarify it for me?

 def remove_first(self) -> Any:
       
        curr = self._first
        if curr is None:
            raise IndexError
        else:
            first = curr.item
            self._first = self._first.next
            return first

CodePudding user response:

It seems like your linked list is implemented like this:

List .first --> Item #1 .next ---> Item#2 .next --> Item#3 etc

The code reassigns the .first member variable of the List class to point to Item#2. Thus if you iterate through the list starting from .first the Item#1 is no longer "in the list". It also decrements the refcount for Item#1 which will deallocate it when refcount goes to zero.

  •  Tags:  
  • Related