Python自定义LinkedList元素迁移与打印功能问题排查
自定义LinkedList字符串元素迁移问题修复
问题根因
你的删除逻辑存在两处漏洞,导致连续字符串节点漏删:
- 修改头结点后没有校验新头结点的类型,若开头存在连续字符串节点会漏删
- 删除
temp.next节点后直接将temp后移,没有校验新的temp.next是否为字符串,连续字符串节点会残留(你遇到的oop1残留就是这个原因:33后连续两个字符串asp、oop1,删除asp后直接将temp移到oop1节点,没有校验这个节点的类型)
修正后的迁移函数
def izdvoji(linkedLista): linked = LinkedList() # 第一步:收集所有字符串节点到新链表 temp = linkedLista.head while temp is not None: if isinstance(temp.data, str): linked.append(temp.data) temp = temp.next # 第二步:删除原链表中所有字符串节点 # 先处理头结点,直到头结点不是字符串 while linkedLista.head is not None and isinstance(linkedLista.head.data, str): linkedLista.head = linkedLista.head.next # 处理后续节点 current = linkedLista.head while current is not None and current.next is not None: if isinstance(current.next.data, str): # 删除节点后current不后移,继续检查新的next current.next = current.next.next else: # 只有当前next不是字符串才后移 current = current.next return linked
运行验证
替换原函数后运行测试用例:
if __name__ == '__main__': L = Lista([33, "asp","oop1",5,21,"python",2,"c++"]) ispis(izdvoji(L)) ispis(L)
输出结果符合预期:
asp oop1 python c++ ------ 33 5 21 2 ------
内容的提问来源于stack exchange,提问作者BillGejc
相关产品推荐
相关产品推荐

