了解与Python的链接列表



我正在与python的链接列表进行自我研究。我正在尝试努力尝试可视化链接列表的结构和概念。以下是自我研究的代码,要求我添加丢失的代码。可以抽出一些人或解释我应该如何想象这一点。我熟悉常规的python列表,dict和其他常见数据结构。但是例如,对于方法,我的思考过程是

if current:
    return current.value
else:
    return None

但这是不正确的。我是否检查构造函数初始化了一个列表并具有元素变量电流?以下是完整的代码。谢谢。

"""The LinkedList code from before is provided below.
Add three functions to the LinkedList.
"get_position" returns the element at a certain position.
The "insert" function will add an element to a particular
spot in the list.
"delete" will delete the first element with that
particular value.
Then, use "Test Run" and "Submit" to run the test cases
at the bottom."""
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."""
        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."""
        pass

    def delete(self, value):
        """Delete the first node with a given value."""
        pass
# Test cases
# Set up some Elements
e1 = Element(1)
e2 = Element(2)
e3 = Element(3)
e4 = Element(4)
# Start setting up a LinkedList
ll = LinkedList(e1)
ll.append(e2)
ll.append(e3)
# Test get_position
# Should print 3
print ll.head.next.next.value
# Should also print 3
print ll.get_position(3).value
# Test insert
ll.insert(e4,3)
# Should print 4 now
print ll.get_position(3).value
# Test delete
ll.delete(1)
# Should print 2 now
print ll.get_position(1).value
# Should print 4 now
print ll.get_position(2).value
# Should print 3 now
print ll.get_position(3).value

对于该方法,我的思考过程是...

什么方法?get_positioninsertdelete

@jacobirr所建议的,添加一种打印链接列表的方法可能会有所帮助。看看:

class Element:
    def __init__(self, value):
        self.value = value
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None
    def append(self, value):
        element = Element(value)
        if self.head is None:
            self.head = element
            return
        cursor = self.head
        while cursor.next is not None:
            cursor = cursor.next
        cursor.next = element
    def __str__(self):
        values = []
        cursor = self.head
        while cursor is not None:
            values.append(cursor.value)
            cursor = cursor.next
        return " -> ".join(values)

def main():
    linked_list = LinkedList()
    linked_list.append("Foo")
    linked_list.append("Bar")
    linked_list.append("Fizz")
    linked_list.append("Buzz")
    print(linked_list)
    return 0

if __name__ == "__main__":
    import sys
    sys.exit(main())

输出:

Foo -> Bar -> Fizz -> Buzz

您需要做的一切:

首先是,尝试可视化将这种状态更改为此时将发生的事情,或者喜欢 - 在纸上甚至在任何在线软件中写下整个可视化以了解更改。

最后/最后,请确保您知道链接列表的核心概念,并对其进行一些棘手的操作。或者,您可以在 google 上搜索一些资源。

好吧,这是我为您的问题做的解决方案:

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):
        counter = 1
        current = self.head
        if position < 1:
            return None
        while current and counter <= position:
            if counter == position:
                return current
            current = current.next
            counter += 1
        return None
    def insert(self, new_element, position):
        counter = 1
        current = self.head
        if position > 1:
            while current and counter < position:
                if counter == position - 1:
                    new_element.next = current.next
                    current.next = new_element
                current = current.next
                counter += 1
        elif position == 1:
            new_element.next = self.head
            self.head = new_element
    def delete(self, value):
        current = self.head
        previous = None
        while current.value != value and current.next:
            previous = current
            current = current.next
        if current.value == value:
            if previous:
                previous.next = current.next
            else:
                self.head = current.next

# Test cases
# Set up some Elements
e1 = Element(1)
e2 = Element(2)
e3 = Element(3)
e4 = Element(4)
# Start setting up a LinkedList
ll = LinkedList(e1)
ll.append(e2)
ll.append(e3)
# Test get_position
# Should print 3
print(ll.head.next.next.value)
# Should also print 3
print(ll.get_position(3).value)
# Test insert
ll.insert(e4,3)
# Should print 4 now
print(ll.get_position(3).value)
# Test delete
ll.delete(1)
# Should print 2 now
print(ll.get_position(1).value)
# Should print 4 now
print(ll.get_position(2).value)
# Should print 3 now
print(ll.get_position(3).value)

再次,任何进一步的问题;拿纸,写代码并可视化发生的事情。

相关内容

  • 没有找到相关文章

最新更新