」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在 Python 中實作單向鍊錶

如何在 Python 中實作單向鍊錶

發佈於2024-11-02
瀏覽:887

How to Implement Singly Linked List in Python

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

class LinkedList:
    def __init__(self):
        self.head = None

    def add_front(self,value):
        new_node = Node(value)
        new_node.next = self.head
        self.head = new_node
    def add_back(self,value):
        new_node = Node(value)
        if self.head is None:
            self.head = new_node
        else:
            current = self.head
            while current.next is not None:
                current = current.next
            current.next = new_node
    def print_list(self):
        current = self.head
        while current is not None:
            print(current.value)
            current = current.next

list1 = LinkedList()

list1.add_front(1)
list1.add_front(2)
list1.add_back(3)
list1.print_list()

1。節點類別:

  • 表示鍊錶中的單一元素。
  • 每個節點有兩個屬性:value儲存數據,next指向清單中的下一個節點。
  • 當一個節點被創建時,它的next指標被設定為None。

2.鍊錶類別:

  • 管理鍊錶操作。
  • 有一個屬性頭,它是鍊錶的起點。最初,由於列表為空,所以 head 設定為 None。

3. add_front方法:

  • 將新節點加入到鍊錶的前面。
  • 使用給定值建立一個新節點。
  • 新節點的下一個指標設定為鍊錶的目前頭。
  • 然後將清單的頭部更新為新節點。

4。 add_back方法:

  • 將新節點加入到鍊錶末尾。
  • 使用給定值建立一個新節點。
  • 如果鍊錶為空(即head為None),則將新節點設為head。
  • 如果鍊錶不為空,則遍歷到鍊錶末尾,然後更新最後一個節點的next指標指向新節點。

5。 print_list 方法:

  • 列印鍊錶中從頭到尾的所有值。
  • 從頭部開始,使用next指標迭代每個節點,直到到達末尾(None),列印每個節點的值。

6。用法範例:

  • 創建了 LinkedList 的實例。
  • add_front 被呼叫兩次,將值為 1 和 2 的節點加入到清單的前面。
  • add_back 被呼叫以將值為 3 的節點加到列表末尾。
  • print_list 被調用,列印鍊錶中所有節點的值。輸出為2,1,3,說明節點新增正確。
版本聲明 本文轉載於:https://dev.to/thirumalesh/how-to-implement-singly-linked-list-in-python-40kc?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3