微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用python在链表类中插入和获取位置

如何解决使用python在链表类中插入和获取位置

我是数据结构和算法的新手。我是一名自学成才的 Python 程序员。我正在做一个关于它的课程,我想制作一个链表,获取链表中的特定位置,插入和删除列表中的元素。 所以我写了我的代码,对我来说,这似乎很好。它没有给我任何错误,但它也没有执行。

这是我写的代码

class Element(object):
    def __init__(self,value):
        self.value = value
        self.next = None
        
class LinkedList(object):
    def __init__(self,head=None):
        self.head = head
        
    def append(self,new_element):
        current = self.head
        if self.head:
            while current.next:
                current = current.next
            current.next = new_element
        else:
            self.head = new_element
            
    def get_position(self,position):
        """Get an element from a particular position.
        Assume the first position is "1".
        Return "None" if position is not in the list."""
        
        current = self.head
        if self.head:
            while current.next:
                if current == position:
                    return current
                else:
                    continue
        
        else:
            return None
    
    def insert(self,new_element,position):
        """Insert a new node at the given position.
        Assume the first position is "1".
        Inserting at position 3 means between
        the 2nd and 3rd elements."""
        
        current = self.head
        if self.head:
            while current.next:
                if current.next == position:
                    current.next = new_element
                    break
                else:
                    continue
        else:
            self.head = new_element

错误是在获取位置函数和插入函数

谁能告诉我我做错了什么? 是循环有问题还是什么? 请帮帮我,我将不胜感激!!谢谢。

解决方法

get_position 中的一些问题:

  • current == position 不是您需要验证的条件。 position 是一个数字,current 是一个元素,因此它们并没有真正进行比较。您需要验证 position 是 1 还是 2,...取决于您在列表中的位置。
  • 循环永远不会前进 current 到下一个节点。所以这代表了一个无限循环。
  • while 条件不应检查 current.next,而是 current。否则,您将永远不会检查列表中的最后一个节点。

这是您更正的代码:

def get_position(self,position):
    if position < 1:  # Just in case the position is too small
        return
    current = self.head
    while current and position > 1:
        position -= 1
        current = current.next
    return current

因此,只要位置减少到 1,或者没有更多节点,循环就会结束。在后一种情况下,返回值将为 None

虽然您的问题是关于 get_position 函数,但您的 insert 也有同样的问题。最重要的是,它还会错误地处理 head 情况。当提供的位置为 1 时,它也应该更改 head

insert 方法实际上可以利用上面的函数找到应该在要插入的节点之前的节点:

def insert(self,new_element,position):
    if position == 1:
        new_element.next = self.head
        self.head = new_element
    else:
        before = self.get_position(position-1)
        if before is None:
            raise ValueError("invalid position")
        new_element.next = before.next
        before.next = new_element

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。