Deleting a node in Linked List in python

让人想犯罪 __ 提交于 2019-12-07 08:31:51

问题


To delete a node in a linked list, what is wrong with this implementation?:

def delete(self, val):
    tmp = self.head
    prev = None
    while tmp: 
        if val == tmp.data:
            self.size -= 1
            if prev==None: 
                self.head = self.head.next 
            else:
                prev.next = tmp.next 
        else:
            prev = tmp
            tmp = tmp.next 

All the guides I've looked at say it should be:

def delete(self, data):
    tmp = self.head
    prev = None
    found = False 
    while tmp and not found:
        if data == tmp.data:
            found = True
        else:
            prev = tmp
            tmp = tmp.next
    if found:
        self.size -= 1
        if prev == None:
            self.head = self.head.next
        else:
            prev.next = tmp.next

but I can't figure out why the found is needed. Why is the found necessary? Why is this implementation more correct?

Additionally, I have the same trouble with search:

My implementation is:

def __contains__(self, data):
    tmp = self.head
    while tmp:
        if data == tmp.data:
            return True 
        else: 
            tmp = tmp.next
    return False 

but the correct implementation is:

def __contains__(self, data):
        tmp = self.head
        found = False
        while tmp and not found:
            if data == tmp.data:
                found = True
            else: 
                tmp = tmp.next
        return found 

回答1:


The deletes are identical as long as data is unique. So it is in general better, do separate looping through the list, from working on elements. It is more readable, and less nested. It would be still better, to give an error, if data is not found:

def delete(self, data):
    tmp = self.head
    prev = None
    while tmp:
        if data == tmp.data:
            break
        prev = tmp
        tmp = tmp.next
    else:
        raise ValueError('data not found')
    self.size -= 1
    if prev is None:
        self.head = tmp.next
    else:
        prev.next = tmp.next


来源:https://stackoverflow.com/questions/32124723/deleting-a-node-in-linked-list-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!