The goal is to remove the last node of a linked list. (Python) The code that I have written only added to the list instead of taking the tail away. I'm not sure if the error is coming from this part here self.head.next.prev = None. I tried refining that part but another error would occurred. What I have posted is only small section of the code.
def remove_tail(self):
if self.tail == self.head:
self.head = None
self.tail = None
elif self.head is not None:
self.head.next.prev = None
self.tail = self.head.next
print("\n=========== PROBLEM 2 TESTS ===========")
ll.remove_tail()
print(ll) # linkedlist[5, 4, 3, 2, 2, 2, 1, 0]
ll.remove_tail()
print(ll) # linkedlist[5, 4, 3, 2, 2, 2, 1]
I reverse the names of head and tail to see of that was causing the issues.
elif self.head is not None:
self.head.next.prev = None
self.tail = self.head.next
Here is the updated code. Errors still occur when I run it.
def remove_tail(self):
if self.tail == self.head:
self.head = None
self.tail = None
if self.tail is not None:
self.tail = self.tail.prev
self.tail.next = None
self.head.next.prev = NoneThis code assumes that there are only two nodes. Why would you assume that?