不少的教材都是用C語言實現鏈表,由於c有指針,能夠很方便的控制內存,很方便就實現鏈表,其餘的語言,則沒那麼方便,因爲python是動態語言,能夠直接把對象賦值給新的變量,因而在python一切皆爲對象的原理上實現鏈表的各項操做。前端
在實現鏈表python類的屬性和方法操做以前,先整理一些鏈表的理論知識。node
鏈表是經過一個個節點(Node)組成的,每一個節點都包含了稱爲數據域(value)和指針域(next)的基本單元,它也是一種遞歸的數據結構。它能保持數據之間的邏輯順序,但存儲空間沒必要按照順序存儲。 python
鏈表的基本元素有:segmentfault
3、單向鏈表屬性與各種操做方法代碼數組
#先定一個node的類 class Node(): #value + next def __init__ (self, value = None, next = None): self._value = value self._next = next def getValue(self): return self._value def getNext(self): return self._next def setValue(self,new_value): self._value = new_value def setNext(self,new_next): self._next = new_next #實現Linked List及其各種操做方法 class LinkedList(): def __init__(self): #初始化鏈表爲空表 self._head = Node() self._tail = None self._length = 0 #檢測是否爲空 def isEmpty(self): return self._head == None #add在鏈表前端添加元素:O(1) def add(self,value): newnode = Node(value,None) #create一個node(爲了插進一個鏈表) newnode.setNext(self._head) self._head = newnode #append在鏈表尾部添加元素:O(n) def append(self,value): newnode = Node(value) if self.isEmpty(): self._head = newnode #若爲空表,將添加的元素設爲第一個元素 else: current = self._head while current.getNext() != None: current = current.getNext() #遍歷鏈表 current.setNext(newnode) #此時current爲鏈表最後的元素 #search檢索元素是否在鏈表中 def search(self,value): current=self._head foundvalue = False while current != None and not foundvalue: if current.getValue() == value: foundvalue = True else: current=current.getNext() return foundvalue #index索引元素在鏈表中的位置 def index(self,value): current = self._head count = 0 found = None while current != None and not found: count += 1 if current.getValue()==value: found = True else: current=current.getNext() if found: return count else: raise ValueError ('%s is not in linkedlist'%value) #remove刪除鏈表中的某項元素 def remove(self,value): current = self._head pre = None while current!=None: if current.getValue() == value: if not pre: self._head = current.getNext() else: pre.setNext(current.getNext()) break else: pre = current current = current.getNext() #insert鏈表中插入元素 def insert(self,pos,value): if pos <= 1: self.add(value) elif pos > self.size(): self.append(value) else: temp = Node(value) count = 1 pre = None current = self._head while count < pos: count += 1 pre = current current = current.getNext() pre.setNext(temp) temp.setNext(current)
鏈表的基本操做:遍歷next節點 數據結構
不能夠用head來遍歷列表 app
學習參考:Python數據結構鏈表實現學習