1. 程式人生 > >python基本數據結構棧stack和隊列queue

python基本數據結構棧stack和隊列queue

mat show prev 序列 lan object 反序 pty order

1,棧,後進先出,多用於反轉

Python裏面實現棧,就是把list包裝成一個類,再添加一些方法作為棧的基本操作。

棧的實現:

class Stack(object):
    #初始化棧為空列表
    def __init__(self):
        self.items = []    #self.__items = []可以把items變成私有屬性

    #判斷棧是不是為空
    def isEmpty(self):
        return len(self.items) ==0

    #返回棧頂的元素
    def peek(self):
        return self.items[-1]

    
#返回棧的大小 def size(self): return len(self.items) #給棧加入新元素 def push(self,a): self.items.append(a) #刪除棧頂的元素 def pop(self): return self.items.pop()

棧應用實例:十進制轉化為二進制

def divideBy2(decNumber):
    remstack = Stack()    #實例化一個棧,因為需要棧結構來存儲數據,也是為了用到棧方法

    while
decNumber > 0: rem = decNumber%2 #除二倒取余法,最後反轉拼接所有的余數 remstack.push(rem) #余數依次放到棧中儲存起來 decNumber = decNumber // 2 binstring = ‘‘ while not remstack.is_empty(): binstring = binstring + str(remstack.pop()) #反序獲取棧中的元素 return binstring print divideBy2(10)

2 隊列queue

隊列實際上就是一個包裝了的列表,從list[0]添加新元素,用pop()來獲取,符合先進先出的規則。

class Queue:
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def enqueue(self,item):    #添加一個新元素item到隊列的開頭,這叫隊尾
        self.items.insert(0,item)

    def dequeue(self):    #減去一個最後一個元素,這叫隊首
        return self.items.pop()

    def size(self):
        return len(self.items)

    def show(self):    #自主添加的,好跟蹤查看隊列裏有啥
        return self.items

隊列應用實例:熱土豆

#就是一隊人圍著圈報數,從0開始,報到m就出局,看誰活最久。
from pythonds.basic.queue import Queue

def HotPotato(namelist,num):
    simqueue =  Queue()
    for name in namelist:
        simqueue.enqueue(name)    #把先namelist添加到隊列中去,ps:從下標是0的位置開始添加,整個插入完成以後序列就反過來了
    while simqueue.size()>1:
        for i in range(num):    #
            simqueue.enqueue(simqueue.dequeue())
            #從列表的末尾減去什麽就把什麽添加到列表開頭
        simqueue.dequeue()    #哪個排最後哪個就是熱土豆,直接出局
    return simqueue.dequeue()

print  HotPotato([lili,jiajia,dahu,wangba,daqing,tamato,potato,hehe],3)

3 雙端隊列有點類似於列表,不多贅述

4,鏈表

基本鏈表的實現: #鏈表是環環相扣形成的序列結構,每一環首先定義self變量,其次要標記下一個變量。所以訪問的時候只能按照順序來。

class Node:   
    def __init__(self,initdata):
        self.data = initdata
        self.next = None

    def getData(self):
        return self.data

    def getNext(self):
        return self.next

    def setData(self,newdata):
        self.data = newdata

    def setNext(self,newnext):
        self.next = newnext

無序鏈表:

class UnorderedList:

    def __init__(self):
        self.head = None    #表示鏈表的頭部不引用任何內容

    def isEmpty(self):
        return self.head == None

    def add(self,item):    #鏈表中有兩個屬性,一個是本身,一個是next,
        temp = Node(item)    #這個設定了鏈表本身,也就是data,無序鏈表也是由node構成的
        temp.setNext(self.head)    #這個設定了next
        self.head = temp    #把鏈表的data參數設定為無序列表的頭----head

    def size(self):
        current = self.head
        count = 0
        while current != None:
            count = count +1
            current = current.getNext()
        return count

    def search(self,item):
        current = self.head
        found = False
        while current != None and not found:
            if current.getData() == item:
                found = True
            else:
                current = current.getNext()
            return found

    def remove(self,item):
        current = self.head
        previous=None
        found = False
        while not found:    #找到要刪除的item以後會跳出循環,此時current.getData()是要刪除的項目
            if current.getData()==item:
                found=True
            else:
                previous=current
                current=current.getNext()
        if previous ==None:    #只有一種情況下,previous會是None,那就是要刪除的是第一個,也就是想刪除self.head
            self.head=current.getNext()
        else:
            previous.setNext(current.getNext())    # 本來的指向是previous.getData()--item(也就是previous.getNext(),還是current.getData())--current.getNext()
#要想刪除item,那就把previous的指向改成current.getNext(),這樣item就不能在原來的鏈表中瞎摻和了

有序鏈表:

class OrderedList:
    def __init__(self):
        self.head = None

    def isEmpty(self):    #同無序列表
        return self.head == None

    def show(self):    
        current = self.head
        while current != None:
            print current.getData()
            current = current.getNext()

    def __iter__(self):
        current = self.head
        while current != None:
            yield current.getData()
            current = current.getNext()

    def size(self):    #同無序列表
        current = self.head
        count = 0
        while current != None:
            count +=1
            current =current.getNext()
        return count

    def search(self,item):    #默認從小到大排列的鏈表
        current = self.head
        found = False
        stop = False
        while current != None and not found and not stop:
            if current.getData() == item:
                found = True
            else:
                if current.getData() > item:
                    stop = True
                else:
                    current = current.getNext()
        return found

    def add(self,item):
        current = self.head
        previous = None
        stop = False
        while current != None and not stop:    #有一個以上元素的情況
            if current.getData() > item:
                stop = True
            else:
                previous = current
                current = current.getNext()    #不用擔心元素添加到最後的情況,因為鏈表中自帶None封住了兩頭

        temp = Node(item)
        if previous == None:    #添加到鏈表頭的情況
            temp.setNext(self.head)
            self.head=temp
        else:
            temp.setNext(current)
            previous.setNext(temp)

    def remove(self, item):
        current = self.head
        previous = None
        found = False
        while not found:
            # 叠代每一項,得到要刪除的那個,並且通過賦值前一個執行刪除
            if current.getData() == item:
                found = True
            else:
                previous = current
                current = current.getNext()
        if previous == None:
            # 如果刪除的是第一項,那麽把第二項變成第一項,否則給previous賦值
            self.head = current.getNext()
        else:
            previous.setNext(current.getNext())

python基本數據結構棧stack和隊列queue