python 数据结构与算法——栈

栈的python实现

数组实现

class Stack:
    def __init__(self):
        self.items = []
         
    def push(self, item):
        self.items.append(item)
         
    def pop(self):
        return self.items.pop()
     
    def isEmpty(self):
        return len(self.items) == 0
     
    def peek(self):
        return self.items[-1]
     
    def __str__(self):
        return str(self.items)

链表实现

class Node:
    def __init__(self):
        self._data = None
        self._next = None

    @property
    def data(self):
        return self._data

    @data.setter
    def data(self, data):
        self._data = data

    @property
    def next(self):
        return self._next

    @next.setter
    def next(self, next):
        self._next = next

    def has_next(self):
        return self._next != None

class Stack(object):
    def __init__(self, data=None):
        self.head = None
        if data:
            for data in data:
                self.push(data)

    def push(self, data):
        temp = Node()
        temp.data = data
        temp.next = self.head
        self.head = temp

    def pop(self):
        if self.head is None:
            raise IndexError('stack is empty')
        temp = self.head.data
        self.head = self.head.next
        return temp

    def peek(self):
        if self.head is None:
            raise IndexError('stack is empty')
        return self.head.data

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

栈的应用

1. 检测字符串中的左右括号是否匹配

def matches(top, symbol):
    openingSymbols = "({["
    closingSymbols = ")}]"  
    return openingSymbols.index(top) == closingSymbols.index(symbol)
 
 
def checkSymbolBalance(inputStr):
    symbolstack = Stack()
    for symbol in inputStr:
        if symbol in ["(", "{", "["]:
            symbolstack.push(symbol)
        elif symbol in [")", "}", "]"]:
            if symbolstack.isEmpty():
                return False
            else:
                topSymbol = symbolstack.pop()
                if not matches(topSymbol, symbol):
                    return False

    return symbolstack.isEmpty()
 
assert( checkSymbolBalance("000[000[") == False)
assert( checkSymbolBalance("000]000[") == False)
assert( checkSymbolBalance("000]000]") == False)
assert( checkSymbolBalance("000[000]") == True)
assert(checkSymbolBalance("{{([][])}()}") == True)

2. 中缀表达式改后缀表达式

def infixToPostfix(infixexpr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()

    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and (prec[opStack.peek()] >= prec[token]):
                  postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    return " ".join(postfixList)

assert(infixToPostfix("A * B + C * D") == "A B * C D * +")
assert(infixToPostfix("( A + B ) * C - ( D - E ) * ( F + G )") == "A B + C * D E - F G + * -")

3. 基于后缀表达式的符号计算

def postfixEval(postfixExpr):
    operandStack = Stack()
    tokenList = postfixExpr.split()

    for token in tokenList:
        if token in "0123456789":
            operandStack.push(int(token))
        else:
            operand2 = operandStack.pop()
            operand1 = operandStack.pop()
            result = doMath(token, operand1, operand2)
            operandStack.push(result)
    return operandStack.pop()

def doMath(op, op1, op2):
    if op == "*":
        return op1 * op2
    elif op == "/":
        return op1 / op2
    elif op == "+":
        return op1 + op2
    else:
        return op1 - op2

assert(postfixEval(infixToPostfix('( 1 + 2 ) * ( 3 - 4 )')) == -3)
发布了274 篇原创文章 · 获赞 446 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/itnerd/article/details/103881610
今日推荐