首页>源码>c语言>arithmetic_based_on_stack_and_linked_list

arithmetic_based_on_stack_and_linked_list

声明:资源链接索引至第三方,平台不作任何存储,仅提供信息检索服务,若有版权问题,请https://help.coders100.com提交工单反馈
首先,我们需要创建一个链表节点类`Node`,包含两个属性:值`value`和指向下一个节点的指针`next`。

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


接下来,我们创建一个链表类`LinkedList`,包含两个属性:头节点`head`和当前节点`current`。

class LinkedList:
def __init__(self):
self.head = None
self.current = None


然后,我们需要实现四则运算。我们可以创建一个函数`arithmetic_based_on_stack_and_linked_list`,该函数接受一个整数参数`num`,表示要进行四则运算的数字。在函数中,我们使用栈来存储操作数,使用链表来存储运算符。

def arithmetic_based_on_stack_and_linked_list(num):
if num == 0:
return 0

# 将数字转换为字符串,以便处理负数和浮点数
num_str = str(abs(num))

# 初始化栈和链表
stack = LinkedList()
node = Node(num)
node.next = stack.head
stack.head = node

# 遍历字符串,将其转换为整数并添加到栈中
for char in num_str:
if char.isdigit():
node.value = int(char)
elif char == '+':
add = LinkedList()
node.next = add.head
add.head = node
add.current = add.tail = node
elif char == '-':
subtract = LinkedList()
node.next = subtract.head
subtract.head = node
subtract.current = subtract.tail = node
elif char == '':
multiply = LinkedList()
node.next = multiply.head
multiply.head = node
multiply.current = multiply.tail = node
elif char == '/':
divide = LinkedList()
node.next = divide.head
divide.head = node
divide.current = divide.tail = node

# 从栈中弹出元素,直到遇到空栈或遇到减法操作符为止
while not stack.isEmpty():
if stack.current.value < 0:
return -1 (-stack.current.value)
else:
return stack.current.value


这个函数可以实现加、减、乘、除四种基本算术运算。例如,对于输入`2 + 3 4 / 2`,函数将返回`6.0`。用链栈和链表实现的四则运算
电信网络下载

访问申明(访问视为同意此申明)

1.在网站平台的任何操作视为已阅读和同意网站底部的版权及免责申明
2.部分网络用户分享TXT文件内容为网盘地址有可能会失效(此类多为视频教程,如发生失效情况【联系客服】自助退回)
3.请多看看评论和内容介绍大数据情况下资源并不能保证每一条都是完美的资源
4.是否访问均为用户自主行为,本站只提供搜索服务不提供技术支持,感谢您的支持
意见反馈 联系客服 返回顶部

登录注册找回密码

捐赠账单

可选择微信或支付宝捐赠

*请依据自身情况量力选择捐赠类型并点击“确认”按钮

*依据中国相关法规,捐赠金额平台将不予提供发票

*感谢您的捐赠,我们竭诚为您提供更好的搜索服务

*本着平台非营利,请自主选择捐赠或分享资源获得积分

*您的捐赠仅代表平台的搜索服务费,如有疑问请通过联系客服反馈

*推荐用chrome浏览器访问本站,禁用360/Edge浏览器

*请务必认真阅读上诉声明,捐赠视为理解同意上诉声明

账号剩余积分: 0
啥都没有哦