數據結構之鏈表詳解——python實現

爲什麼使用鏈表

鏈表結構可以充分利用計算機內存空間,實現靈活的內存動態管理。

鏈表的定義

鏈表(Linked List )是一種很常見的數據結構,鏈表也是一種線性表,他不像順序表一樣連續存儲,而是在每個數據節點上會存放下一個節點的地址信息,通過這樣的方式把每個數據節點鏈接起來。
在這裏插入圖片描述

單向鏈表

單向鏈表也叫單鏈表,是鏈表中最簡單的一種形式,它的每個節點包含兩個域,一個信息域(元素域)和一個鏈接域。這個鏈接指向鏈表中的下一個節點,而最後一個節點的鏈接域則指向一個空值。
在這裏插入圖片描述

  • 表元素域elem用來存放具體的數據。
  • 鏈接域next用來存放下一個節點的位置(python中的標識)
  • 變量p指向鏈表的頭節點(首節點)的位置,從p出發能找到表中的任意節點。

節點實現

class SingleNode(object):
	#單鏈表的節點
	def __init__(self,item):
		 # _item存放數據元素
		self.item=item
		# _next是下一個節點的標識
		self.next=None

單鏈表的操作

  • is_empty() 鏈表是否爲空
  • length() 鏈表長度
  • travel() 遍歷整個鏈表
  • add(item) 鏈表頭部添加元素
  • append(item) 鏈表尾部添加元素
  • insert(pos, item) 指定位置添加元素
  • remove(item) 刪除節點
  • search(item) 查找節點是否存在

單鏈表的實現

class SingleLinkList(object):
	#初始化,定義好頭結點
	def __init__(self):
		self.__head=None
		
	#判斷鏈表是否爲空	
	def is_empty(self):
		return seif.__head is None
		
	def length(self):
        """鏈表長度"""
        count=0
        cur=self.__head
        while cur != None:
        	count+=1
        	cur=cur.next
        return count
	 
	def travel(self):
        """遍歷鏈表"""
        cur=self.__head
        while cur!=None:
        	print (cur.item,end=" ")
        	cur=cur.next

頭部添加元素

在這裏插入圖片描述

def add(self, item):
        """頭部添加元素"""
        node=SingleNode(item)
        # 將新節點的鏈接域next指向頭節點,即_head指向的位置
        node.next=self.head.next
        # 將鏈表的頭_head指向新節點
        self.head=node

尾部添加元素

 def append(self, item):
        """尾部添加元素"""
        node=SingleNode(item)
        # 先判斷鏈表是否爲空,若是空鏈表,則將_head指向新節點
        if self.is_empty():
        	self.head=node
        # 若不爲空,則找到尾部,將尾節點的next指向新節點
        else:
	        cur=self.head
	        while cur.next !=None
	        	cur=cur.next
	        cur.next=node

指定位置添加元素

在這裏插入圖片描述

 def insert(self, pos, item):
        """指定位置添加元素"""
        # 若指定位置pos爲第一個元素之前,則執行頭部插入
        if pos<=0:
        	self add(item)
         # 若指定位置超過鏈表尾部,則執行尾部插入
         elif pos>=(self.length()-1):
         	self.append(item)
         # 找到指定位置
         else:
         	node=SingleNode(item)
         	count=0
         	pre=self.__head
         	while count<(pos-1):
         		count+=1
         		pre=pre.next
         	node.next=pre.next
         	pre.next=node

刪除節點

在這裏插入圖片描述

def remove(self,item):
        """刪除節點"""
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章