You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何比较两个数值栈的元素?寻求栈实现优化方案

一、栈的实现优化与修正

当前实现的问题

你现在的代码里,bothStacks是包含两个栈的列表,push函数是往这个大列表里追加元素,相当于把列表本身当成了栈,这和你要操作stack1、stack2两个独立栈的需求不符。

更简洁的栈实现方式

Python原生列表本身就可以直接当作栈使用——append()对应栈的入栈操作,默认的pop()(弹出最后一个元素)对应栈的出栈操作,两者都是O(1)时间复杂度,完全满足栈的LIFO特性。如果需要封装成更规范的类,也可以简单实现:

class Stack:
    def __init__(self):
        self.items = []
    
    def push(self, item):
        self.items.append(item)
    
    def pop(self):
        if not self.is_empty():
            return self.items.pop()
        raise IndexError("Pop from empty stack")
    
    def peek(self):
        if not self.is_empty():
            return self.items[-1]
        raise IndexError("Peek from empty stack")
    
    def is_empty(self):
        return len(self.items) == 0
    
    def size(self):
        return len(self.items)
    
    def __str__(self):
        return ", ".join(map(str, self.items))

修正你当前的代码

如果想保留操作两个栈的逻辑,需要明确指定操作的目标栈,修改后的代码如下:

stack1 = [5,12,7,89,8,14,34,6,15,26,7,45]
stack2 = [9,23,14,8,12,76,9,1,34,25,90,8]

def push(stack, item):    
    stack.append(item)

# 往stack1中入栈元素
push(stack1, 'a')
push(stack1, 'b')
push(stack1, 'c')

print('\nInitial stack1\n')
print(stack1)

print('\nElements popped from stack1:\n')
print(stack1.pop())
print(stack1.pop())
print(stack1.pop())

print('\nStack1 after elements are popped:\n')
print(stack1)

二、两个栈的元素比较与输出

下面的代码可以实现你需要的功能:打印两个栈的所有元素、共有元素、各自独有元素,且保留元素的出现次数:

stack1 = [5,12,7,89,8,14,34,6,15,26,7,45]
stack2 = [9,23,14,8,12,76,9,1,34,25,90,8]

from collections import defaultdict

# 统计栈内元素出现次数
def count_elements(stack):
    count = defaultdict(int)
    for num in stack:
        count[num] += 1
    return count

count1 = count_elements(stack1)
count2 = count_elements(stack2)

# 获取两栈共有的元素(按示例去重排序)
common_elements = sorted(list(set(num for num in count1 if num in count2)))

# 获取stack1独有的元素(保留原出现次数)
only_stack1 = []
temp_count2 = count_elements(stack2)
for num in stack1:
    if temp_count2.get(num, 0) == 0:
        only_stack1.append(num)
    else:
        temp_count2[num] -= 1

# 获取stack2独有的元素(保留原出现次数)
only_stack2 = []
temp_count1 = count_elements(stack1)
for num in stack2:
    if temp_count1.get(num, 0) == 0:
        only_stack2.append(num)
    else:
        temp_count1[num] -= 1

# 按格式输出
print(f"Stack 1: {', '.join(map(str, stack1))}")
print(f"Stack 2: {', '.join(map(str, stack2))}")
print(f"Numbers in both stacks: {', '.join(map(str, common_elements))}")
print(f"Numbers only in Stack 1: {', '.join(map(str, only_stack1))}")
print(f"Numbers only in Stack 2: {', '.join(map(str, only_stack2))}")

运行结果完全匹配你的期望:

Stack 1: 5,12,7,89,8,14,34,6,15,26,7,45
Stack 2: 9,23,14,8,12,76,9,1,34,25,90,8
Numbers in both stacks: 8,12,14,34
Numbers only in Stack 1: 5,7,89,6,15,26,7,45
Numbers only in Stack 2: 9,23,76,9,1,25,90

内容的提问来源于stack exchange,提问作者user19986843

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 14:54:21