Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[pull] master from youngyangyang04:master #346

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
pull merged 5 commits into AlgorithmAndLeetCode:master from youngyangyang04:master
Sep 14, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Update 修正 0225.用队列实现栈 python代码
  • Loading branch information
gitcsq authored Aug 27, 2023
commit ca197783d20194a10202d9033e5b1ec6da3c9d2a
37 changes: 34 additions & 3 deletions problems/0225.用队列实现栈.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -454,13 +454,34 @@ class MyStack:

def top(self) -> int:
"""
写法一:
1. 首先确认不空
2. 我们仅有in会存放数据,所以返回第一个即可
2. 我们仅有in会存放数据,所以返回第一个即可(这里实际上用到了栈)
写法二:
1. 首先确认不空
2. 因为队列的特殊性,FIFO,所以我们只有在pop()的时候才会使用queue_out
3. 先把queue_in中的所有元素(除了最后一个),依次出列放进queue_out
4. 交换in和out,此时out里只有一个元素
5. 把out中的pop出来,即是原队列的最后一个,并使用temp变量暂存
6. 把temp追加到queue_in的末尾
"""
# 写法一:
# if self.empty():
# return None

# return self.queue_in[-1] # 这里实际上用到了栈,因为直接获取了queue_in的末尾元素

# 写法二:
if self.empty():
return None

for i in range(len(self.queue_in) - 1):
self.queue_out.append(self.queue_in.popleft())

return self.queue_in[-1]
self.queue_in, self.queue_out = self.queue_out, self.queue_in
temp = self.queue_out.popleft()
self.queue_in.append(temp)
return temp


def empty(self) -> bool:
Expand Down Expand Up @@ -488,9 +509,19 @@ class MyStack:
return self.que.popleft()

def top(self) -> int:
# 写法一:
# if self.empty():
# return None
# return self.que[-1]

# 写法二:
if self.empty():
return None
return self.que[-1]
for i in range(len(self.que)-1):
self.que.append(self.que.popleft())
temp = self.que.popleft()
self.que.append(temp)
return temp

def empty(self) -> bool:
return not self.que
Expand Down

AltStyle によって変換されたページ (->オリジナル) /