【发布时间】:2019-08-02 18:33:01
【问题描述】:
我正在使用 Python 对链表进行自学。我正在努力尝试将链表的结构和概念可视化。下面是来自自学的代码,要求我添加缺失的代码。有人可以画出或解释我应该如何想象这个。我熟悉常规的 Python 列表、字典和其他常见的数据结构。但例如对于方法,我的思考过程是
if current:
return current.value
else:
return None
但这是不正确的。我是否在检查构造函数是否初始化了一个列表并有一个元素变量 current?以下是完整代码。谢谢。
"""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
【问题讨论】:
-
我建议创建一个
print_list函数来打印出一组链表节点,如下所示:1->2->3->4,因此您可以随时调用此函数来帮助可视化链表的状态。
标签: python linked-list