我正在学习数据结构和算法,并开始学习如何在python中从头开始构建链表。现在,我了解了它们是如何工作的,以及制作它们的组件(节点、数据/地址、头/尾等(,但在python中构建它们时,我很难理解它们的功能。就像我在python中有工作代码来制作它们一样,但我不知道它们如何与类一起操作背后的逻辑。例如,我在addLast函数中对节点变量(node=node(value((如何连接到node类感到困惑。
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def addLast(self, value):
node = Node(value)
if self.head == None:
self.head = node
self.tail = node
else:
self.tail.next = node
self.tail = node
class Node:
def __init__(self, value, next=None):
self.value = value
# NODE POINTS TO THE NEXT ELEMENT IF PROVIDED ELSE NONE
self.next = next
class LinkedList:
def __init__(self):
# INIT AN EMPTY LINKED LIST
self.head = None
self.tail = None
def addLast(self, value):
# CREATE A NODE OBJECT WITH VALUE 'value' WHICH POINTS TO NOTHING (because it's the end of the linked list)
node = Node(value)
# IF NO HEAD IT BECOMES THE HEAD AND THE TAIL
if self.head == None:
self.head = node
self.tail = node
else:
# ADD THE NODE TO THE END (tail) OF THE LINKED LIST
self.tail.next = node
self.tail = node
# Create an empty linked_list
head = Linked_list()
# Add at the end a node with the value 1
head.addLast(1)
希望它对你来说更清楚,如果需要的话可以提问
我认为这可能有助于您理解代码在场景中的实际作用。
您可以将以下代码粘贴到链接,然后单击">可视化执行";按钮它将一步一步地可视化所有细节。
祝你好运!
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def addLast(self, value):
node = Node(value)
if self.head == None:
self.head = node
self.tail = node
else:
self.tail.next = node
self.tail = node
head = LinkedList()
head.addLast(1)
head.addLast(2)