【发布时间】:2021-03-21 10:21:22
【问题描述】:
我是数据结构和算法的新手。我是一名自学成才的 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函数和insert函数
谁能告诉我我做错了什么? 循环有问题吗? 请帮助我,我将不胜感激!!谢谢。
【问题讨论】:
-
“错误在...”:请提供错误信息并指出在哪一行。
-
我没有收到错误消息,但代码也没有执行。我正在使用 Jupyter Notebook,它只是在我开始执行给定功能时不断加载。
标签: python list algorithm data-structures linked-list