在python的链表中删除节点 [英] Deleting a node in Linked List in python

查看:80
本文介绍了在python的链表中删除节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要删除链表中的节点,此实现有什么问题?:

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?

另外,我在 search 上也遇到了同样的麻烦:

Additionally, I have the same trouble with search:

我的实现是:

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

但正确的实现是:

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 

推荐答案

删除是相同的,只要数据是唯一的即可.因此,总的来说更好的做法是,从列表中分离循环,而不是处理元素.它更具可读性,并且嵌套较少.如果未找到 data ,给出错误仍然会更好:

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

这篇关于在python的链表中删除节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆