求大佬解惑,腾讯笔试
菜鸡一枚
第1题,实现一个队列的操作,用python写的,实在想不明白哪儿错了
def myQueue(): T = input() T = int(T) res=[] myqueue = [] for i in range(T): Q = int(input()) for j in range(Q): line = input() line = line.split() if line[0]=='PUSH': myqueue.insert(0,int(line[1])) if line[0]=='TOP': if not myqueue: #print(-1) res.append(-1) else: res.append(myqueue[-1]) if line[0]=='SIZE': res.append(len(myqueue)) if line[0]=='CLEAR': myqueue = [] if line[0]=='POP': if not myqueue: res.append(-1) else: myqueue.pop() for result in res: print(result)
第四题 两个栈实现队列,同样想不明白 def myQueue2(): stack1 = [] stack2 = [] res=[] n = int(input()) for i in range(n): line = input() line = line.split() if line[0]=='add': stack1.append(int(line[1])) if line[0]=='poll': while stack1: tmp = stack1.pop() stack2.append(tmp) stack2.pop() if line[0]=='peek': while stack1: tmp = stack1.pop() stack2.append(tmp) res.append(stack2[-1]) print(stack2,stack1) for k in res: print(k)
第五题,寻找k层祖父节点 哎~为啥都是case 0 啊~
def findAn(): n = input() n = int(n) res = [] def level(k): index = 0 while k != 0: k = k//2 index += 1 return index for i in range(n): line = input() line = line.split() cur_level = level(int(line[0])) count = cur_level - int(line[1]) number = int(line[0]) if cur_level==int(line[1]): res.append(-1) else: while count > 0: count -= 1 number = number//2 res.append(number) for k in res: print(k)