2021-06-13 19:54

# 为什么第一个while循环条件为False仍会运行？

这是Leetcode的第496题，

pop from emptylist。

``````from Stack_FUO import Stack

def nextGreaterElement(nums1,nums2):
stack = Stack()
res = []
temp = Stack()

for num in nums2:
stack.push(num)

for num in nums1:
isFound = False
nextmax = -1
while (stack.length != 0 and not isFound):
top = stack.pop()
if top > num:
nextmax = top
elif top == num:
isFound = False
temp.push(top)
res.append(nextmax)
while temp.length() != 0:
stack.push(temp.pop())
return res

nums1 = [4,1,2]
nums2 = [1,3,4,2]
print(nextGreaterElement(nums1,nums2))``````

``````class Stack:
def __init__(self):
self.items = []

def isEmpty(self):      # 是否为空
return self.items == []

def push(self,item):    # 入栈
self.items.append(item)

def pop(self):          # 出栈
return self.items.pop()

def peek(self):         # 取栈顶
if len(self.items) != 0:
return self.items[-1]
else:
return None

def clear(self):        # 清空栈
self.items = []

def length(self):       # 查看栈的长度
return len(self.items)``````

• 写回答
• 好问题 提建议
• 关注问题
• 收藏
• 邀请回答

#### 2条回答默认 最新

• 是不是一碗粉 2021-06-13 20:24
已采纳

这啥稀奇古怪的错误啊？

你的循环条件stack.length后面没有加小括号。。。

正确格式为

``````stack.length        # 错误格式
stack.length()      # 正确格式``````
已采纳该答案
评论
解决 无用
打赏 举报
• 是不是一碗粉 2021-06-13 20:28
``````from Stack_FUO import Stack

def nextGreaterElement(nums1,nums2):
stack = Stack()
res = []
temp = Stack()

for num in nums2:
stack.push(num)

for num in nums1:
isFound = False
nextmax = -1
while (stack.length() != 0 and not isFound):
top = stack.pop()
if top > num:
nextmax = top
elif top == num:
isFound = True
temp.push(top)
res.append(nextmax)
while temp.length() != 0:
stack.push(temp.pop())
return res

nums1 = [4,1,2]
nums2 = [1,3,4,2]
print(nextGreaterElement(nums1,nums2))``````
评论
解决 无用
打赏 举报