while(!stack.isEmpty()){int num = stack.pop();System.out.println(num);}
例题
classSolution{publicbooleanisValid(String s){Stack<Character> stack =newStack<>();for(char i:s.toCharArray()){if(i =='('|| i =='['|| i =='{'){
stack.push(i);}else{if(stack.size()==0){returnfalse;}else{char temp = stack.pop();if(i ==')'){if(temp !='('){returnfalse;}}elseif(i ==']'){if(temp !='['){returnfalse;}}else{if(temp !='{'){returnfalse;}}}}}if(stack.size()==0){returntrue;}else{returnfalse;}}}
classSolution:defisValid(self, s:str)->bool:
stack =[]for i in s:if i =="("or i =="["or i =="{":
stack.append(i)else:iflen(stack)==0:returnFalseelse:
temp = stack.pop()if i ==")":if temp !="(":returnFalseelif i =="]":if temp !="[":returnFalseelif i =="}":if temp !="{":returnFalseiflen(stack)==0:returnTrueelse:returnFalse
classSolution:defnextGreaterElement(self, nums1: List[int], nums2: List[int])-> List[int]:
res =[]
stack =[]for i in nums2:
stack.append(i)for num in nums1:
temp =[]
isFound =Falsemax=-1while(len(stack)!=0and isFound ==False):
top = stack.pop()if top > num:max= top
elif top == num:
isFound =True
temp.append(top)
res.append(max)while(len(temp)!=0):
stack.append(temp.pop())return res