数据结构链表之单向链表:Python3 实现单向链表——1
生活随笔
收集整理的這篇文章主要介紹了
数据结构链表之单向链表:Python3 实现单向链表——1
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Python3 實現單向鏈表
鏈表定義與簡介
- 定義:鏈表與順序表(Python中列表)性質相反,鏈表是物理單元上非順序的、非連續的,在邏輯順序上其數據元素是通過指針實現的,組成鏈表的每一個元素也可以叫做鏈表的節點,節點可以在運行時動態生成
單向鏈表中所有的元素也可以稱之為節點,每個節點包含兩個區域,如上圖item區域稱為數據域,next區域為指針域,單向鏈表中尾節點的判斷只需判斷該節點的指針(next)是否指向空即可。
鏈表(Linked list)與順序表(Sequence list)的主要差異:
- 順序表的內存地址是連續的,其數據元素有對應唯一的索引,搜索時非常方便,但進行元素插入時較麻煩,每次插入元素,其后所有元素都要移動一位。
- 而鏈表內存地址是非連續、非順序的,邏輯順序由指針實現,在插入元素時只需將指定位置的前一個元素的指針斷開,并指向要插入的元素的節點,然后插入的元素指針再指向下一個節點即可,但是在查詢元素時,需要從頭結點開始一個一個遍歷尋找。
由于鏈表不是必須按順序存儲,鏈表在插入的時候可以達到O(1)的復雜度,比線性表順序表快得多,但是查找一個節點或者訪問特定編號的節點則需要O(n)的時間,而線性表和順序表相應的時間復雜度分別是O(logn)和O(1)。
定義單鏈表
# 定義節點 class Node:def __init__(self, item):self.item = itemself.next = None# 定義鏈表 class SingleLinkList:def __init__(self):self._head = Noneif __name__ == '__main__':# 創建鏈表link_list = SingleLinkList()# 創建結點node1 = Node(1)node2 = Node(2)# 將結點添加到鏈表link_list._head = node1# 將第一個結點的next指針指向下一結點node1.next = node2# 訪問鏈表print("head", link_list._head) # 訪問第一個結點數據print(link_list._head.item) # 訪問第一個結點數據print(link_list._head.next.item) # 訪問第二個結點數據一個簡單的鏈表,沒有增刪改查等功能,操作十分不便
接下來對其,進行一部分常用功能實現:
代碼實現
class Node:"""The nodes of single linked list"""def __init__(self, item):self.item = itemself.next = Noneclass SingleLinkedList:def __init__(self):"""Initialize the head and the length of single linked list"""self.head = Nonedef clear(self):"""CLear a linked list"""self.head = Nonedef show_items(self):"""Show all the elements of linked list"""if self.is_empty():return Nonecur = self.headwhile cur.next:yield cur.itemcur = cur.nextyield cur.itemdef get_value_by_index(self, index):"""Get a value by index"""node = self.headindex = self.length()+index if index < 0 else indexif index < 0:raise IndexError('index out of range')try:for i in range(index):node = node.nextreturn node.itemexcept AttributeError as e:raise IndexError('index out of range')def is_empty(self):"""Judge if a linked list is empty"""return self.head is Nonedef length(self):"""Return the elements number of a linked list"""cur = self.headif not cur:return 0count = 1while cur.next:count += 1cur = cur.nextreturn countdef insert(self, index, item):"""Insert an element before the given index of a node"""node = Node(item)length = self.length()# Empty list, append directlyif not self.head:self.append(item)if index < 0 and (index + length) >= 0:index += length# index>0if index > 0:cur = self.headwhile cur.next:if index <= 1:breakcur = cur.nextindex -= 1node.next = cur.nextcur.next = nodeelif index == 0 or index + length < 0:temp = self.headnode.next = tempself.head = nodedef append(self, item):"""Append elements to the end of a linked list"""node = Node(item)if self.is_empty():self.head = nodeelse:cur = self.headwhile cur.next:cur = cur.nextcur.next = nodedef remove(self, index):"""Remove an element by index"""if not -self.length() - 1 < index < self.length():raise IndexError('remove index out of range')if index < 0:index += self.length()print(f"index", index)if index == 0:print("Get into ")self.head = self.head.nextelse:cur = self.headpre = curwhile index > 0:pre = curcur = cur.nextindex -= 1pre.next = cur.nextdef is_exist(self, item):"""Judge if an element in linked-list"""return item in self.show_items()def indexOf(self, item):"""Return a given item's index where is the first appearance in the list"""return list(self.show_items()).index(item)驗證功能
if __name__ == '__main__':SLL = SingleLinkedList()print(f"If the linked list is empty?: {SLL.is_empty()}")# Append elements to the endfor i in range(5):SLL.append(i)print(f"Show all items:{list(SLL.show_items())}")print(f"The length of {SLL.__class__.__name__}: {SLL.length()}")# _index>0_index, _item = 9, 11SLL.insert(_index, _item)print(f"Insert {_item} before linked list[{_index}]: {list(SLL.show_items())}")# _index=0_index, _item = 0, 22SLL.insert(_index, _item)print(f"Insert {_item} before linked list[{_index}]: {list(SLL.show_items())}")# _index<0 and length+_index>0_index, _item = -3, 33SLL.insert(_index, _item)print(f"Insert {_item} before linked list[{_index}]: {list(SLL.show_items())}")# _index<0 and length+_index<0_index, _item = -21, 44SLL.insert(_index, _item)print(f"Insert {_item} before linked list[{_index}]: {list(SLL.show_items())}")_index = -5SLL.remove(_index)print(f"Remove an element by index[{_index}]: {list(SLL.show_items())}")# Get a value by index, if index out of range, throw a IndexError_index = 3print(f"Get a value by index[{_index}], its value: {SLL.get_value_by_index(3)}")_item = 44print(f"If item:[{_item}] in linked list {SLL.__class__.__name__}? {SLL.is_exist(_item)} ")# CLear a linked listprint(f"The linked list has been cleared: {SLL.__class__.__name__}: {SLL.clear()}")print(f"The length of {SLL.__class__.__name__}: {SLL.length()}")結果
If the linked list is empty?: True Show all items:[0, 1, 2, 3, 4] The length of SingleLinkedList: 5 Insert 11 before linked list[9]: [0, 1, 2, 3, 4, 11] Insert 22 before linked list[0]: [22, 0, 1, 2, 3, 4, 11] Insert 33 before linked list[-3]: [22, 0, 1, 2, 33, 3, 4, 11] Insert 44 before linked list[-21]: [44, 22, 0, 1, 2, 33, 3, 4, 11] Remove an element by index[-5]: [44, 22, 0, 1, 33, 3, 4, 11] Get a value by index[3], its value: 1 If item:[44] in linked list SingleLinkedList? True The linked list has been cleared: SingleLinkedList: None The length of SingleLinkedList: 0 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的数据结构链表之单向链表:Python3 实现单向链表——1的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python工控怎么样_搞工控不了解py
- 下一篇: plt.axis()用法详解