我正在學習資料結構和演算法,并且開始學習如何在 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
uj5u.com熱心網友回復:
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)
希望對您來說更清楚,如果需要,請提出問題
uj5u.com熱心網友回復:
我認為這可以幫助您了解代碼在場景中的實際作用。
您可以將以下代碼粘貼到鏈接中,然后單擊“可視化執行”按鈕。它將逐步可視化所有細節。
祝你好運!
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/525939.html
