Python Forum

Full Version: reference in pop function for linked list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, I have designed two methods, pop1 and pop2, to remove an element from a linked list. Both functions pop1 and pop2 manages two cases:

1) if the element to be removed is the head of the list
2) if the element to be removed is NOT the head of the list

The difference between pop1 and pop2 functions is how they manage the case 1). The only difference is that in pop1, I store the pointer of 'self.head' in 'current', and use 'current' to change the pointer to the next element, while in pop2 I use directly the pointer 'self.head' to change the pointer to the next element. However, the function pop1 is not working, while the function pop2 is working. Why? From my understanding, in pop1 when I execute the line 'current = self.head', 'current' should be the pointer of 'self.head' and then be able to change the next pointer, but this is not happening. After calling the function pop1 to remove the first element of the list, the list actually does not change.

class CircularLinkedList:
  def __init__ (self):
    self.head = None
  
  def pop1 (self, x):
    if self != None:

      current = self.head
      
      # if the element to be removed is the head of the list
      if current.data == x: 
        current = current.next

      # if the element to be removed is NOT the head of the list
      else:
        prev = self
        while current != None:
          if current.data == x:
            prev.next = current.next
          prev = current
          current = current.next


  def pop2 (self, x):
      if self != None:

        current = self.head
      
        # if the element to be removed is the head of the list
        if self.head.data == x: 
          self.head = self.head.next

        # if the element to be removed is NOT the head of the list
        else:
          prev = self
          while current != None:
            if current.data == x:
              prev.next = current.next
            prev = current
            current = current.next
but if I replace 'self.head' with 'current' it is not working anymore. From my understanding, 'current' contains the pointer to 'self.head', so it should modify the pointer in case the value to be deleted is in the first position of the list.