日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

数据结构链表之单向链表:Python3 实现单向链表——1

發布時間:2024/7/5 python 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 数据结构链表之单向链表: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) # 訪問第二個結點數據

一個簡單的鏈表,沒有增刪改查等功能,操作十分不便

接下來對其,進行一部分常用功能實現:

  • 清空元素clear(),斷開頭結點的指針,長度為0
  • 展示元素的值show_items()
  • 獲取元素get_value_by_index(),以偏移量獲取元素的值,超出偏移量會報錯IndexErorr,可以是負偏移
  • 判斷鏈表是否為空is_empty()
  • 返回鏈表長度length()
  • 在指定位置插入insert(),當超過實際長度,在最后插入;當為負數倒序選擇插入,負數的絕對值大于實際長度則在最前面插入
  • 在末尾追加元素append()
  • 指定偏移量移除元素remove(),超過偏移量,拋出IndexErorr,可以使用負偏移
  • 判斷一個元素是否存在于鏈表is_exist(),存在返回True,否則返回False
  • 返回元素的偏移indexOf()
  • 代碼實現

    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的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。

    主站蜘蛛池模板: 黄色网页网站 | 国产一区二区视频免费在线观看 | 久久久天堂国产精品女人 | 欧美bbbbbbbbbbbb精品 | 先锋资源中文字幕 | av男人的天堂网 | 91视频在| 不许穿内裤随时挨c调教h苏绵 | 激情在线网站 | 久久久久人妻精品一区二区三区 | 性一交一乱一伧国产女士spa | 久热国产精品视频 | 大肉大捧一进一出好爽mba | 狠狠干b | 伊人网色 | 亚洲三级视频在线观看 | 99在线看| 精品热久久| 国产一区不卡在线 | 97色伦影院 | 欧美日韩精品一二三区 | 欧美久久一区二区三区 | 黄色av网址在线 | 国产精品久久久精品三级 | 精品久久久久一区二区国产 | 日韩中文字幕av | 亚洲欧美激情小说另类 | 精品久久久久久 | 另类老妇性bbwbbw图片 | 久久免费精品视频 | 国产在线播放av | 久艹av | 91九色视频在线 | 伊伊成人 | 国产精品伦一区 | 窝窝在线视频 | 色先锋在线 | 狠狠干2024 | 国产区一区二区 | 成人伊人 | 免费91网站 | 欧美亚洲精品天堂 | 香蕉久久国产av一区二区 | 天海翼一二三区 | av在线播放中文字幕 | 一眉道姑| 少妇在线 | 亚洲成色在线 | 在线a网 | 国产精品99精品无码视亚 | 九一天堂 | 香港三级日本三级韩国三级 | 欧美日韩激情网 | 久久青青操| 日韩大片在线免费观看 | 久草在现 | 美女网站全黄 | 人人爽人人插 | 男女做网站 | 久久久久亚洲av无码网站 | 涩涩在线播放 | 日韩av在线网站 | 青草久久久久 | 国产欧美精品一区二区三区app | 国产成人精品一区 | 欧美精品日韩少妇 | 欧美黑人猛交 | 韩国三级av | 姐姐你真棒插曲快来救救我电影 | 操大爷影院 | 青青视频二区 | 一区二区在线 | 日韩高清二区 | 色版视频在线观看 | 久久国产精品一区 | 色婷婷综合久久久久中文 | 69日本xxxxxxxx96 | 国产伦子伦对白视频 | 中文字幕美女 | 91精品人妻一区二区三区四区 | 超碰xxx| 亚洲丝袜一区 | 久久精品国产精品亚洲毛片 | 久久国产精品首页 | av999| 久久婷婷av| 欧洲成人一区二区三区 | 久久国产一 | 国产高清免费在线 | 欧美一级网站 | 欧美色综合网站 | 免费av的网站 | 在线观看国产免费av | 亚洲人成人无码网www国产 | 中文字幕一区二区人妻在线不卡 | 欧美在线中文字幕 | 蜜臀尤物一区二区三区直播 | 情不自禁电影 | 日本一区二区三区在线观看视频 |