但,,

没有调试通过。

思路是对的,立此存照。

关键就是用链表完全实现列表的功能,

替换了就应该OK的。

# coding = utf-8

# 节点初始化
class Node:
    def __init__(self, init_data):
        self.data = init_data
        self.next = None

    def get_data(self):
        return self.data

    def get_next(self):
        return self.next

    def set_data(self, new_data):
        self.data = new_data

    def set_next(self, new_next):
        self.next = new_next

# 实现列表方法
class UnorderedList:
    def __init__(self):
        # 链表类本身不包含任何节点对象。
        # 它只包含对链接结构中第一个节点的单个引用。
        self.head = None

    def is_empty(self)->bool:
        return self.head is None

    # 加到链表第一项
    def add(self, item):
        temp = Node(item)
        temp.set_next(self.head)
        self.head = temp

    # 加到链表最后一项
    def append(self, item):
        if self.head is None:
            self.add(item)
        else:
            temp = Node(item)
            current = self.head
            previous = None
            while current is not None:
                previous = current
                current = current.get_next()
            previous.set_next(temp)

    # 这个动作和append一样
    def push(self, item):
        self.append(item)

    # 删除链表节点时,需要使用previous保存前一个节点
    def remove(self, item):
        current = self.head
        previous = None
        found = False
        while not found and current is not None:
            if current.get_data() == item:
                found = True
            else:
                previous = current
                current = current.get_next()
        if not found:
            raise Exception("not found.")
        if previous is None:
            self.head = current.get_next()
        else:
            previous.set_next(current.get_next())

    # 经典循环链表节点,并设置哨兵位
    def search(self, item):
        current = self.head
        found = False
        while current is not None and not found:
            if current.get_data() == item:
                found = True
            else:
                current = current.get_next()
        return found

    def size(self):
        current = self.head
        count = 0
        while current is not None:
            count += 1
            current = current.get_next()
        return count

    def index(self, item):
        found = False
        count = 0
        current = self.head
        while current is not None and not found:
            count += 1
            if current.get_data() == item:
                found = True
            else:
                current = current.get_next()
        if not found:
            raise Exception("not found.")
        return count

    def insert(self, pos, item):
        if self.head is None:
            raise Exception("not init")
        elif pos > self.size():
            raise Exception("pos is too large")
        else:
            temp = Node(item)
            current = self.head
            previous = None
            for i in range(pos):
                previous = current
                current = current.get_next()
            temp.set_next(current)
            previous.set_next(temp)

    def pop(self):
        current = self.head
        previous = None
        for i in range(self.size()-1):
            previous = current
            current = current.get_next()
        pop_value = current.get_data()
        previous.set_next(None)
        return pop_value

    def peek(self):
        current = self.head
        previous = None
        while current is not None:
            previous = current
            current = current.get_next()
        return previous.get_data()

    def pop_pos(self, pos):
        current = self.head
        previous = None
        for i in range(pos):
            previous = current
            current = current.get_next()
        pop_value = current.get_data()
        previous.set_next(current.get_next())
        return pop_value

    def show(self):
        current = self.head
        tmp = ''
        while current is not None:
            current = current.get_next()
            tmp += current.get_data()
        return tmp

'''
my_list = UnorderedList()
my_list.add(31)
my_list.add(77)
my_list.add(17)
my_list.add(93)
my_list.add(26)
my_list.add(54)
my_list.add(68)
my_list.append(100)
my_list.append(110)
my_list.insert(2, 57)
print(my_list.pop(), '=========pop===')
print(my_list.pop_pos(5), '=========pop_pos===')
my_list.show()
print(my_list.peek(), '=========peek===')
print(my_list.size())
print(my_list.search(68))
try:
    my_list.remove(310)
except Exception as error:
    print(error)

try:
    print(my_list.index(54))
except Exception as error:
    print(error)
my_list.show()
'''

class Stack:
    def __init__(self):
        self.items = UnorderedList()

    # 是否为空
    def is_empty(self):
        return self.items.is_empty()

    # 进栈
    def push(self, item):
        self.items.append(item)

    # 出栈
    def pop(self):
        return self.items.pop()

    # 返回栈顶值,不改变栈
    def peek(self):
        return self.items.peek()

    # 返回栈长度
    def size(self):
        return self.items.size()

def infix_to_postfix(infix_expr):
    prec = dict()
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    prec[")"] = 1
    postfix_expr = []
    s = Stack()
    for item in infix_expr.split():
        # 如果标记是操作数,将其附加到输出列表的末尾
        if item not in prec.keys():
            postfix_expr.append(item)
        # 如果标记是左括号,将其压到 s 上
        elif item == '(':
            s.push(item)
        # 如果标记是右括号,则弹出 s,直到删除相应的左括号。将每个运算符附加到
        # 输出列表的末尾
        elif item == ')':
            while s.peek() != '(':
                postfix_expr.append(s.pop())
            s.pop()
        # 如果标记是运算符, *,/,+  或  -  ,将其压入 s。但是,首先删除已经在
        # s 中具有更高或相等优先级的任何运算符,并将它们加到输出列表中
        else:
            while (not s.is_empty()) \
                    and (prec[s.peek()] >= prec[item]):
                postfix_expr.append(s.pop())
            s.push(item)
        print(s.items.show())
    # 当输入表达式被完全处理时,检查 s。仍然在栈上的任何运算符都可以删除并加到
    # 输出列表的末尾
    while not s.is_empty():
        postfix_expr.append(s.pop())

    return ' '.join(postfix_expr)

def postfix_eval(postfix_expr):
    s = Stack()
    for item in postfix_expr.split():
        # 如果不是运算符号,压栈
        if item not in '+-*/':
            s.push(item)
        else:
            # 如果是运算符号,取出栈上最近两个数字进行运算
            # 然后,再将结果压回栈
            op2 = int(s.pop())
            op1 = int(s.pop())
            print(op1, item, op2)
            result = do_match(item, op1, op2)
            s.push(result)
        print(s.items.show())
    return result

# 运行结果
def do_match(op, op1, op2):
    if op == '+':
        return op1 + op2
    elif op == '-':
        return op1 - op2
    elif op == '*':
        return op1 * op2
    elif op == '/':
        return op1 / op2
    else:
        raise Exception('Error operation!')

infix_str = '( 23 + 2 ) * 5 - 280 / ( 4 + 11 * 6 - 35 )'

postfix_output = infix_to_postfix(infix_str)
print(infix_str)
print(postfix_output)
postfix_result = postfix_eval(postfix_output)
print(postfix_result)

  

python---自己来打通节点,链表,栈,应用的更多相关文章

  1. Python与数据结构[1] -> 栈/Stack[0] -> 链表栈与数组栈的 Python 实现

    栈 / Stack 目录 链表栈 数组栈 栈是一种基本的线性数据结构(先入后出FILO),在 C 语言中有链表和数组两种实现方式,下面用 Python 对这两种栈进行实现. 1 链表栈 链表栈是以单链 ...

  2. Python递归_打印节点信息

    Python递归_打印节点信息 递归特性:1.必须由一个明确的结束条件2.每次进入更深一层递归时,问题规模相比上一次递归都应该有所减少3.递归效率不高,递归层次过多会导致栈溢出(在计算机中,函数调用时 ...

  3. java——链表、链表栈 LinkedListStack、链表队列 LinkedListQueue

    LikedList: package Date_pacage; public class LinkedList<E> { public static void main(String[] ...

  4. python算法与数据结构-单链表(38)

    一.链表 链表是一种物理存储单元上非连续.非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的.链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成.每个结点包括 ...

  5. python中的数据结构-链表

    一.什么是链表 链表是由一系列节点构成,每个节点由一个值域和指针域构成,值域中存储着用户数据,指针域中存储这指向下一个节点的指针.根据结构的不同,链表可以分为单向链表.单向循环链表.双向链表.双向循环 ...

  6. C语言 复杂的栈(链表栈)

    //复杂的栈--链表栈 #include<stdio.h> #include<stdlib.h> #define datatype int//定义链表栈数据类型 //定义链表栈 ...

  7. Leetcode:面试题 04.03. 特定深度节点链表

    Leetcode:面试题 04.03. 特定深度节点链表 Leetcode:面试题 04.03. 特定深度节点链表 先贴一下自己写过一个模板,按层数遍历: https://www.cnblogs.co ...

  8. Python手写模拟单向链表对象,栈对象和树

    单向链表: class error(Exception): def __init__(self,msg): super(error,self).__init__() self.msg=msg def ...

  9. [转]为什么python标准库没有实现链表

    实际上刚开始学习一些高级语言的时候我也有同样的疑问,而且即使有链表对应物的语言,链表常常也很少被实际使用.如果是在国外听数据结构的课,老师一般会警告你这只是一个理论概念,实际应用应该实际考察,在通常情 ...

随机推荐

  1. 【转】python3解析库lxml

    转自:http://www.cnblogs.com/zhangxinqi/p/9210211.html 阅读目录 1.python库lxml的安装 2.XPath常用规则 (1)读取文本解析节点 (2 ...

  2. xv6 + Qemu 在Ubuntu下编译运行教程【转】

    转自:https://blog.csdn.net/yinglang19941010/article/details/49310111 如果想要离线看教程,可以下载该 文档 一.使用工具说明 1.    ...

  3. 多线程内存问题分析之mprotect方法【转】

    转自:https://blog.csdn.net/agwtpcbox/article/details/53230664 http://www.yebangyu.org/blog/2016/02/01/ ...

  4. Python3学习笔记02-基础语法

    默认情况下,Python 3 源码文件以 UTF-8 编码,所有字符串都是 unicode 字符串 ' # -*- coding:cp-1252 -*-' 也可以指定其他编码,以上用cp-1252字符 ...

  5. git与eclipse集成之clone远程仓库到本地

    1. Git与Eclipse集成 1.1. Clone远程仓库到本地 1.1.1.        获取远程仓库地址(选择北京,访问速度比深圳快) 1.1.2.        将远程仓库导入到Eclip ...

  6. python pip下载速度慢的解决方法

    pip是python内置的非常好用的下载工具,基本可以下载全部的python库.它还有一个非常好的特点,当你安装一个库的时候,它会自动帮你安装所有这个库的依赖库.完全一键式操作.非常方便.但是由于pi ...

  7. MySQL - 查看慢SQL

    查看MySQL是否启用了查看慢SQL的日志文件 (1) 查看慢SQL日志是否启用 mysql> show variables like 'log_slow_queries'; +-------- ...

  8. Linux内存使用调整

    前段时间在做播放器的时候,遇到个问题,花了很长时间,做个记录,希望对有需要的人有所帮助: 播放器的播视频的时候,无论是手动切换视频还是到视频播放完成,自动切换视频,一定次数后均出现黑屏现象,偶尔有声音 ...

  9. 单点登录SSO的原理及实现方式总结

      核心思想   用户信息的集中存储(全局Cooike.集中式Session.Json Web Token.Redis缓存服务器.自定义SSO服务器)   认证(Filter中执行)   登出(不同站 ...

  10. html<meta>标签

    1. 定义说明 <meta>提供与页面有关的元数据,元数据是对数据的描述 <meta>总是位于<head></head>中 <meta>定义 ...