如下图,共3题,要求用Python语言实现,初学数据结构内容没有什么头绪,求指导教学,非常感谢!
按道理从东往西简单些,但因为旅行者是从西往东走,那设计思路如下:
1.假设数组为[8,10,3,6,5]
则将数组中的数依次入队列que,用栈来保存湖景房
先出队,在出队的时候判断栈是否为空,栈不空的时候,不停地检测当前出队的房高是否高于栈顶的房高,如果高就出栈,直到不高于栈项的房高为止,最后将当前出队的房高入栈。
2. 示例
import queue
A = [8, 10, 3, 6, 5]
que = queue.deque()
for i in A:
que.append(i)
stack = list()
while que:
t = que.popleft()
while stack:
if t > stack[-1]:
stack.pop()
else:
break
stack.append(t)
print(stack)
"""--result
[10, 6, 5]
"""
我靠,这么多题我还以为只有一题
图裂开了
from random import randint
import queue
houses = [randint(10,30) for _ in range(10)]
# 队列
queue_a = queue.Queue(len(houses))
for i in houses:
queue_b = queue.Queue(len(houses))
while not queue_a.empty():
temp = queue_a.get()
if i < temp:
queue_b.put(temp)
else:
break
queue_b.put(i)
queue_a = queue_b
# 栈
stack_a = queue.LifoQueue(len(houses))
for i in houses:
while not stack_a.empty():
temp = stack_a.get()
if i < temp:
stack_a.put(temp)
break
stack_a.put(i)
print(houses)
while not queue_a.empty():
print(queue_a.get())
while not stack_a.empty():
print(stack_a.get())