0

I have below code. I am trying to delete the last node. But the node is not getting deleted. The temp is still holding the all the data. I did not understand that, in Python the assignment means deep copy or shallow copy?

class ll:
    def __init__(self, data):
        self.data = data
        self.next = None
    def adddata(self, data):
        if not self.next:
            self.next = ll(data)
            return
        self.next.adddata(data)
def display(root):
    if root == None:
        return
    print root.data
    display(root.next)

def delete_last(root):
    temp = root
    myfrontptr = root.next
    while myfrontptr.next != None:
        root = root.next
        myfrontptr = myfrontptr.next
    if root.next != None and myfrontptr.next == None:
        del myfrontptr
    return temp

l = ll(1)
l.adddata(5)
l.adddata(3)
l.adddata(2)
l.adddata(0)
l.adddata(4)
l = delete_last(l)
display(l)
Rasmi Ranjan Nayak
  • 11,510
  • 29
  • 82
  • 122
  • 1
    `del` doesn't mean "delete this object". It means "unset this variable". You unset the `myfrontptr` local variable, but that doesn't do anything to the list. – user2357112 Jun 30 '16 at 17:26
  • It's almost never useful to `del` a variable. – user2357112 Jun 30 '16 at 17:27
  • Not related to your question, but it seems odd you create an old style class. In python 2.7 you need to declare `class ll(object)` if you want (and you do -- don't you??!!) new style classes – joel goldstick Jun 30 '16 at 17:42

2 Answers2

2

Instead of using del, you should unreference the last node.

Replace

if root.next != None and myfrontptr.next == None:
    del myfrontptr

With

if root.next != None and myfrontptr.next == None:
    root.next = None
Garrett Hyde
  • 5,409
  • 8
  • 49
  • 55
  • `del` wont be helpful? If Yes, what about `myfrontptr` it is still in the memory. So, `Python ` will take care of it by its own? or we need to delete it? – Rasmi Ranjan Nayak Jun 30 '16 at 17:36
  • Python's garbage collector will take care of it. `del` in mainly used when you want to remove an object from a list or dictionary. – Garrett Hyde Jun 30 '16 at 21:58
1

You forgot to set next reference in element before last element when last element is removed:

def delete_last(root):
    temp = root
    myfrontptr = root.next
    while myfrontptr.next != None:
        root = root.next
        myfrontptr = myfrontptr.next
    if root.next != None and myfrontptr.next == None:
        del myfrontptr # you don't need this, myfrontptr is a local name anyway
        root.next = None
    return temp

del does not remove anything from memory. Unline in C/C++, in python memory is freed by Garbage Collector. And even in C/C++ you'd have to overwrite the last element pointer/reference.

Community
  • 1
  • 1
Jezor
  • 3,253
  • 2
  • 19
  • 43