zoukankan      html  css  js  c++  java
  • 栈的算法实现

    class Stack(object):
    
        def __init__(self):
            self.pTop = None
            self.pBottom = None
    
    
    class Node(object):
        def __init__(self, data=None, pNext=None):
            self.data = data
            self.pNext = pNext
    
    
    def pushStack(s, pNew):
        pNew.pNext = s.pTop
        s.pTop = pNew
    
    
    def popStack(s):
        cur = s.pTop
        while cur != s.pBottom:
            s.pTop = cur.pNext
            print("出栈的元素是:%s" % cur.data)
            cur = cur.pNext
        else:
            print("出栈失败")
    
    
    def showAll(s):
        cur = s.pTop
    
        while cur != s.pBottom:
            print("元素是:%s" % cur.data)
            cur = cur.pNext
    
    
    def isEmpty(s):
        if s.pTop == s.pBottom:
            print("the stack is empty")
            return True
        return False
    
    
    def clearStack(s):
        """
        和pop的区别在于,pop让python来清空引用计数为0的数据
        clear要我们手动清空
        :param s:
        :return:
        """
        if isEmpty(s):
            return None
        cur = s.pTop
        q = None
        while cur != s.pBottom:
            q = cur.pNext
            del cur
            cur = q
        else:
            s.pBottom = s.pTop
    
    
    s = Stack()
    p = Node()
    s.pTop = s.pBottom = p
    
    n1 = Node(4)
    pushStack(s, n1)
    
    n2 = Node(5)
    pushStack(s, n2)
    
    n3 = Node(6)
    pushStack(s, n3)
    
    n4 = Node(2)
    pushStack(s, n4)
    
    print("**********遍历元素***************")
    showAll(s)
    
    # print("************出栈*****************")
    # popStack(s)
    
    print("*************清空栈*************")
    clearStack(s)
    
    
  • 相关阅读:
    算法之路 level 01 problem set
    算法原理与实践(链表)
    散列表(HashTable)
    系统设计与实践(实战演练)
    桶排序 + 基数排序
    算法原理与实践(二叉树)
    Total Difference String
    【翻译】std::list::remove
    【翻译】std::remove
    Observer模式实践
  • 原文地址:https://www.cnblogs.com/qiaoqianshitou/p/9928108.html
Copyright © 2011-2022 走看看