python數據結構之鏈表


鏈表(Linked List)

很多的教材都是用C語言實現鏈表,因為c有指針,可以很方便的控制內存,很方便就實現鏈表,其他的語言,則沒那么方便,由於python是動態語言,可以直接把對象賦值給新的變量,於是在python一切皆為對象的原理上實現鏈表的各項操作。

在實現鏈表python類的屬性和方法操作之前,先整理一些鏈表的理論知識。

一、鏈表的基本結構

鏈表是通過一個個節點(Node)組成的,每個節點都包含了稱為數據域(value)和指針域(next)的基本單元,它也是一種遞歸的數據結構。它能保持數據之間的邏輯順序,但存儲空間不必按照順序存儲。 

鏈表的基本元素有:

  • 節點:每個節點有兩個部分,左邊部分稱為值域,用來存放用戶數據;右邊部分稱為指針域,用來存放指向下一個元素的指針。
  • head:head節點永遠指向第一個節點
  • tail: tail永遠指向最后一個節點
  • None:鏈表中最后一個節點的指針域為None值

二、鏈表的種類以及和動態數組(Array List)的對比

 

三、單向鏈表屬性與各類操作方法代碼

#先定一個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)

四、操作鏈表的原理知識

1.遍歷鏈表

    鏈表的基本操作:遍歷next節點 

  • 在列表中查找一個元素 
  • 在列表中插入一個元素
  • 從列表中刪除一列元素

    不可以用head來遍歷列表 

  • 否則會丟失列表的一些節點 
  • 可以使用和head相同類型的索引變量:current

2.插入

3.刪除

4.雙向鏈表

5.循環鏈表

 

學習參考:Python數據結構鏈表實現

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM