Home > OS >  How to delete last Node of the list using next
How to delete last Node of the list using next

Time:11-02

I try to remove last Node from the list but get following error no matter how I twist it: --- line 108, in remove_last before.nxt = delete.nxt AttributeError: 'NoneType' object has no attribute 'nxt'---

Here is my code:

@dataclass
class Node:
   value: int = None
   nxt: Any = None  


 @dataclass
 class Deque:
     head: Node = None      
     tail: Node = None      
     size: int = 0

     def remove_last(self):
        if self.head is None:
            print("empty queue")
            return None
        else:
            before = self.head
            for i in range(self.size-1):
               before = before.nxt
            delete = before.nxt
            before.nxt = delete.nxt
            self.size -= 1
            return before.value

Why can I not apply next?

CodePudding user response:

I think you miscounted and forgot about the singleton case:

def remove_last(self):
    if self.head is None:  # empty
        print("empty queue")
        return None
    if self.head is self.tail:  # one element (there can still be no `before`)
        val = self.head.value
        self.head = self.tail = None
        self.size = 0 
        return val
    before, delete = self.head, self.head.nxt
    while delete.nxt:  # why rely on size (but it should be size-2 iterations)
       before, delete = before.nxt, delete.nxt
    before.nxt = None
    self.size -= 1
    return delete.value

As indicated in the comments, the general case case would require size-2 iterations. Simplest case: 2 elements, then before would be self.head, which means 0 iterations.

CodePudding user response:

This is how I solved it. It was None because I was jumping to the next node after last node, which didn't exist

      else:
        node = self.head
        for i in range(self.size-2):
           node = node.nxt
        node.nxt = None
       
  • Related