搜尋
首頁後端開發Python教學Python程式:在鍊錶的第一個和最後一個位置加入元素

Python程式:在鍊錶的第一個和最後一個位置加入元素

在Python中,鍊錶是一種線性資料結構,它由一系列節點組成,每個節點包含一個值和對鍊錶中下一個節點的引用。

在本文中,我們將討論如何在Python中將元素新增至鍊錶的第一個和最後一個位置。

Linked List in Python

鍊錶是一種引用資料結構,用於儲存一組元素。它在某種程度上類似於數組,但是在數組中,資料儲存在連續的記憶體位置中,而在鍊錶中,資料不受此條件限制。這意味著資料不是按順序存儲,而是以隨機的方式儲存在記憶體中。

This raises one question that is, how we can access the elements in a linked list? The answer is quite intuitive in linked list one element points to another till the end of the list.

清單的開頭和結尾被視為特殊位置。清單的開頭稱為頭部,它指向第一個元素,而最後一個元素則是特殊之處在於它指向NULL

Head -> data_1 -> data_2 -> … -> data_n -> NULL

現在我們知道如何存取鍊錶的開頭和結尾,讓我們看看如何遍歷元素並存取鍊錶中的資料。

遍歷鍊錶非常簡單,我們只需從頭開始存取下一個節點;我們不斷重複這個過程,直到找到一個下一個節點為NULL的節點。至於存取節點中的數據,我們使用箭頭運算符“->”。

Head->data

現在我們已經具備了所有必要的理解來開始解決這個問題。

在開頭新增元素

To add the data at the beginning of the linked list, we must take into consideration the head of the linked list. Whenever we add a node at the beginning of the linked list, the linked list will be ified with the newlymod node being the first node / head of the list.

Algorithm

Step 1 – Create the new node

#步驟 2 - 在新建立的節點中新增資料

Step 3 – Update the link of the new node and make it point to current head node

步驟 4 - 現在將頭指標設定為新建立的節點

注意 - 這些步驟的順序非常重要,因為如果您首先將新建立的節點設定為頭節點,那麼我們將無法更新新節點的鏈接,理想情況下,該連結應該指向先前的頭節點。

Example

class Node:
   def __init__(self, data):
      self.dataPart = data
      self.nextNode = None
class LinkedList:
   def __init__(self):
      self.headNode = None
   def showList(self):
      n = self.headNode
      while n is not None:
         print(n.dataPart, end='-')
         n = n.nextNode
      print('')
   def addBeginList(self, data):
      tempNode = Node(data)
      tempNode.nextNode = self.headNode
      self.headNode = tempNode
newLinkedList = LinkedList()
print("Printing the list before adding element : ")
newLinkedList.showList()
newLinkedList.addBeginList(10)
newLinkedList.addBeginList(25)
print("Printing the elements after adding at the beginning of the list")
newLinkedList.showList()

輸出

Printing the list before adding any element :
\
Printing the elements after adding at the beginning of the list
25-10-\

在最後加上元素

Adding elements at the end, is logically different from adding at the beginning of the list. This time we need to access the last node of the list instead of the first node, i.e., head.

現在的問題是要檢查我們要新增元素的列表是否為空列表,或者它是否已經有一些元素。

If the list is empty then the new node will be the first node for the list, and in the other case, it will be the last node. For that we need to check whether the head node is None or not. The list is treated empty of head is None, and not empty otherwise.

Algorithm

Step 1 – Create a new node.

第二步 - 將資料加入節點的資料部分。

Step 3 – Make sure the next node of the newly created node points to None or Null pointer.

步驟 4 - 如果清單為空,則將新建立的節點作為頭節點。

Step 5 - Else traverse to the end of list, last node.

Step 6 – Set the next node of the last node to the newly created node.

Example

class Node:
   def __init__(self, data):
      self.dataPart = data
      self.nextNode = None
class LinkedList:
   def __init__(self):
      self.headNode = None
   def showList(self):
      n = self.headNode
      while n is not None:
         print(n.dataPart, end='-')
         n = n.nextNode
      print("")
   def addEndList(self, data):
      tempNode = Node(data)
      if self.headNode is None:
         self.headNode = tempNode
      else:
         n = self.headNode
         while n.nextNode is not None:
            n = n.nextNode
            n.nextNode = tempNode
newLinkedList = LinkedList()
print("Printing the list before insertion : ")
newLinkedList.showList()
newLinkedList.addEndList(25)
newLinkedList.addEndList(10)
print("Printing the list after adding elements at the end of the list : ")
newLinkedList.showList()

輸出

Printing the list before insertion :
\
Printing the list after adding elements at the end of the list :
25-10-\

Conclusion

在本文中,我們討論如何使用Python類別來實作一個鍊錶,以及如何在鍊錶中新增元素。我們重點介紹了在清單的開頭和結尾添加元素的方法。

以上是Python程式:在鍊錶的第一個和最後一個位置加入元素的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:tutorialspoint。如有侵權,請聯絡admin@php.cn刪除
Python的科學計算中如何使用陣列?Python的科學計算中如何使用陣列?Apr 25, 2025 am 12:28 AM

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

您如何處理同一系統上的不同Python版本?您如何處理同一系統上的不同Python版本?Apr 25, 2025 am 12:24 AM

你可以通過使用pyenv、venv和Anaconda來管理不同的Python版本。 1)使用pyenv管理多個Python版本:安裝pyenv,設置全局和本地版本。 2)使用venv創建虛擬環境以隔離項目依賴。 3)使用Anaconda管理數據科學項目中的Python版本。 4)保留系統Python用於系統級任務。通過這些工具和策略,你可以有效地管理不同版本的Python,確保項目順利運行。

與標準Python陣列相比,使用Numpy數組的一些優點是什麼?與標準Python陣列相比,使用Numpy數組的一些優點是什麼?Apr 25, 2025 am 12:21 AM

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基於基於duetoc的iMplation,2)2)他們的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函數函數函數函數構成和穩定性構成和穩定性的操作,製造

陣列的同質性質如何影響性能?陣列的同質性質如何影響性能?Apr 25, 2025 am 12:13 AM

數組的同質性對性能的影響是雙重的:1)同質性允許編譯器優化內存訪問,提高性能;2)但限制了類型多樣性,可能導致效率低下。總之,選擇合適的數據結構至關重要。

編寫可執行python腳本的最佳實踐是什麼?編寫可執行python腳本的最佳實踐是什麼?Apr 25, 2025 am 12:11 AM

到CraftCraftExecutablePythcripts,lollow TheSebestPractices:1)Addashebangline(#!/usr/usr/bin/envpython3)tomakethescriptexecutable.2)setpermissionswithchmodwithchmod xyour_script.3)

Numpy數組與使用數組模塊創建的數組有何不同?Numpy數組與使用數組模塊創建的數組有何不同?Apr 24, 2025 pm 03:53 PM

numpyArraysareAreBetterFornumericalialoperations andmulti-demensionaldata,而learthearrayModuleSutableforbasic,內存效率段

Numpy數組的使用與使用Python中的數組模塊陣列相比如何?Numpy數組的使用與使用Python中的數組模塊陣列相比如何?Apr 24, 2025 pm 03:49 PM

numpyArraySareAreBetterForHeAvyNumericalComputing,而lelethearRayModulesiutable-usemoblemory-connerage-inderabledsswithSimpleDatateTypes.1)NumpyArsofferVerverVerverVerverVersAtility andPerformanceForlargedForlargedAtatasetSetsAtsAndAtasEndCompleXoper.2)

CTYPES模塊與Python中的數組有何關係?CTYPES模塊與Python中的數組有何關係?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingingangandmanipulatingc-stylarraysinpython.1)usectypestoInterfacewithClibrariesForperfermance.2)createc-stylec-stylec-stylarraysfornumericalcomputations.3)passarraystocfunctions foreforfunctionsforeffortions.however.however,However,HoweverofiousofmemoryManageManiverage,Pressiveo,Pressivero

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。