使用已学的各种数据结构及基本操作,设计算法revers
使用已学的各种数据结构及基本操作,设计算法reverseOdd,对参数所给定的队列中的整数进行操作,将队列中奇数的顺序进行逆置,偶数的顺序维持不变。例如,给定队列从队头至队尾的元素为:(14, 13, 17, 8, 4, 10, 11, 4,15, 18, 19),调用该函数后,则队列内容变为:(14, 19, 15,8, 4, 10, 11, 4, 17, 18,13).
答案
from collections import deque def reverseOdd(q: deque): stack = [] temp = deque() while q: x = q.popleft() if x % 2 == 1: stack.append(x) else: temp.append(x) # 偶数输出栈里的奇数 if x % 2 == 0: while stack: q.append(stack.pop()) q.append(x) # 处理剩下奇数 while stack: q.append(stack.pop()) while temp: q.append(temp.popleft())