1. 程式人生 > >資料結構及演算法--棧

資料結構及演算法--棧

順序棧

三個基本屬性

  • 棧的儲存資料data

  • 棧的最大儲存量maxSize

  • 棧頂top

Python實現

# Python 2.7

class sqStack(object):

    # 初始化
    def __init__(self, maxSize):
        self.data = [None] * maxSize
        self.maxSize = maxSize
        self.top = -1

    # 獲取順序棧長度  
    def get_length(self):
        return
self.top + 1 # 清空順序棧 def clear(self): for i in range(self.get_length()): self.data[i] = None self.top = -1 # 是否為空 def is_empty(self): return self.top == -1 # 是否滿 def is_full(self): return self.get_length() == self.maxSize # 進棧
def push(self, elem): if self.is_full(): print 'Stack is full!' else: self.top += 1 self.data[self.top] = elem # 出棧 def pop(self): if self.is_empty(): print 'Stack is empty!' else: self.top -= 1
return self.data[self.top + 1] # 取棧頂元素 def get_top(self): if self.is_empty(): print 'Stack is empty!' else: return self.data[self.top] # 由棧頂列印棧元素 def show_stack(self): for i in range(self.get_length()-1, -1, -1): print self.data[i]

鏈式棧

節點的基本屬性

  • 資料域data

  • 後繼指標next

鏈式棧的基本屬性

  • 棧頂

  • 鏈式棧的長度

Python實現

# Python 2.7

# 節點
class Node(object):
    def __init__(self, data, next=None):
        self.data = data
        self.next = next

# 連結串列
class lkStack(object):

    # 初始化
    def __init__(self):
        self.top = Node(None)
        self.length = 0

    # 是否為空
    def is_empty(self):
        return self.length == 0

    # 獲取連結串列長度
    def get_length(self):
        return self.length

    # 進棧
    def push(self, elem):
        node = Node(elem, self.top)
        self.top = node
        self.length += 1

    # 出棧
    def pop(self):
        if self.length == 0:
            print 'lkStack is empty!'
        else:
            top = self.top
            self.top = self.top.next
            self.length -= 1
            return top.data

    # 展示連結串列
    def show(self):
        if self.is_empty():
            print 'lkList is empty!'
        else:
            p = self.top
            for i in range(self.length):
                print p.data
                p = p.next

棧的應用–四則運算表示式求值

字尾(逆波蘭)表示法

  • 中綴表示法:9+(3-1)*3+10/2

  • 字尾表示法:9 3 1 - 3 * + 10 2 / +

中綴轉字尾

# Python 2.7

# 將中綴字串轉換成陣列
def str2list(calc_str):
# calc_str = '9+(3-1)*3+10/2'
    symbol_list = ['+', '-', '*', '/', '(', ')']
    calc_list = [calc_str]
    for symbol in symbol_list:
        str_list = []
        for part in calc_list:
            part_list = part.split(symbol)
            temp = []
            for item in part_list:
                if item:  # 非空時追加
                    temp.append(item)
                temp.append(symbol)
            del temp[-1]
            if temp:  # 非空時追加
                str_list.extend(temp)
        calc_list = str_list
    return calc_list

# 中綴轉字尾
def mid_after(calc_str):    
    mid2after = lkStack()
    mid_list = str2list(calc_str)
    after_list = []
    symbol_list = ['+', '-', '*', '/', '(', ')']
    symbol_value = {'(':-2, None:-1, '+':0, '-':0, '*':1, '/':1}
    for item in mid_list:
        if item not in symbol_list:
            after_list.append(item)
        else:
            if item == ')':
                while mid2after.top.data != '(': 
                    top = mid2after.pop()
                    after_list.append(top)
                top = mid2after.pop()
            else:
                if item == '(':
                    mid2after.push(item)
                else:
                    if symbol_value[item] > symbol_value[mid2after.top.data]:
                        mid2after.push(item)
                    if symbol_value[item] < symbol_value[mid2after.top.data]:
                        while symbol_value[item] <= symbol_value[mid2after.top.data]:
                            top = mid2after.pop()
                            after_list.append(top)
                        mid2after.push(item)
    while not mid2after.is_empty():
        top = mid2after.pop()
        after_list.append(top)
    return after_list

通過後綴表示式求值

# Python 2.7

def after_calc(after_list):
    symbol_list = ['+', '-', '*', '/']
    stack = lkStack()
    for item in after_list:
        if item not in symbol_list:
            stack.push(item)
        else:
            var1 = float(stack.pop())
            var2 = float(stack.pop())
            if item == '+':
                result = var2 + var1
            elif item == '-':
                result = var2 - var1
            elif item == '*':
                result = var2 * var1
            else:
                result = var2 / var1
            stack.push(str(result))
    return float(stack.top.data)

測試

# Python 2.7

calc_str = '12+((12-7)*(11-2)-6)*12'
calc_list = str2list(calc_str)
after_list = mid_after(calc_str)
result = after_calc(after_list)

廣告時間

個人部落格:http://ruanshubin.top
GitHub:https://github.com/Ruanshubin/

這裡寫圖片描述

歡迎您掃一掃上面的二維碼,關注我的微信公眾號!