本博客来自于对左神初级班的笔记整理,个人将java改为Python
1、用固定大小的数组实现一个栈
根据栈先进后出的特性,设置一个指针始终指向数组已存入元素的末尾后一个空缺位置。push时先存入元素指针再后移,pop时指针先前移再取出元素,查看当前栈顶的元素就是返回指针-1对应的值。代码如下:
class ArrayStack:
def __init__(self, N):
self.array = [None]*N
self.n = N # 开辟的固定数组的size
self.size = 0 # 栈中已有数的size
def push(self, value):
if self.size == self.n:
print("The stack is full")
return False
else:
self.array[self.size] = value
self.size += 1
def pop(self):
if self.size == 0:
print("The stack is empty")
return False
else:
value = self.array[self.size-1]
self.array[self.size-1] = None
self.size -= 1
return value
def peak(self): # 返回栈顶元素
if self.size == 0:
print("The stack is empty")
return False
else:
return self.array[self.size-1]
if __name__ == '__main__':
N = int(input())
x = ArrayStack(N)
# 测试
x.push(5)
print(x.peak())
print(x.pop())
2、用固定大小的数组实现一个队列
根据队列先进先出的特性,需要设置两个指针,一个指向出队列的元素,一个指向进队列的位置,同时指针到数组尾端时对数组大小求余,使数组能循环利用。
# 固定大小数组实现队列
class ArrayQueue:
def __init__(self,N):
self.array = [None]*N
self.n = N
self.size = 0
self.first = 0 # 出队列
self.last = 0 # 入队列
def enqueue(self, value):
if self.size == self.n:
print("The queue is full")
return False
else:
self.size += 1
self.array[self.last] = value
self.last = self.last+1 if self.last != self.n - 1 else 0
def dequeue(self):
if self.size == 0:
print("The queue is empty")
return False
else:
self.size -= 1
value = self.array[self.first]
self.first = self.first + 1 if self.first != self.n - 1 else 0
return value
def peak(self):
if self.size == 0:
print("The queue is empty")
return False
else:
return self.array[self.first]
if __name__ == '__main__':
N = int(input())
x = ArrayQueue(N)
# 测试
x.enqueue(5)
print(x.peak())
print(x.dequeue())
x.enqueue(6)
print(x.dequeue())
3、实现一个特殊的栈,在实现栈的基本功能的基础上,再实现返 回栈中最小元素的操作。
【要求】 1.pop、push、getMin操作的时间复杂度都是O(1)。 2.设计的栈类型可以使用现成的栈结构
思路是开辟两个栈,第一个栈保持正常操作,第二个栈如果进入的数比栈顶元素小,就入栈,pop时如果原栈和最小栈定元素相同,则同时删除最小栈中的元素,最后返回最小栈顶元素即为最小值。原题在leetcode上https://leetcode-cn.com/problems/min-stack/
# 返回栈的最小值,时间复杂度为O(1)
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stackData = []
self.minstack = []
def push(self, x: int) -> None:
self.stackData.append(x)
if len(self.minstack)==0 or x <= self.minstack[-1]:
self.minstack.append(x)
def pop(self) -> None:
if len(self.stackData) == 0:
# print("This stack is empty")
return None
else:
value = self.stackData.pop()
if self.minstack[-1] == value:
self.minstack.pop()
return value
def top(self) -> int:
if len(self.stackData) == 0:
return None
else:
return self.stackData[-1]
def getMin(self) -> int:
if len(self.minstack) == 0:
return None
else:
return self.minstack[-1]
if __name__ == '__main__':
minStack =MinStack()
minStack.push(-2)
minStack.push(0)
minStack.push(-3)
print(minStack.getMin()) # -3
print(minStack.pop()) # -3
print(minStack.top()) # 0
print(minStack.getMin()) # -2
4、如何使用队列实现栈结构
按道理来讲,是需要两个队列,每次取栈顶元素的时候,就将一个队列除了最后一个元素之外所有元素全部进入另一个队列中,然后将两队列作交换。但是python中有一个内置的deque,双边队列,可以类似于作弊的行为,直接从list左边取值。此处还是按照两个队列来写。题目地址:https://leetcode-cn.com/problems/implement-stack-using-queues/
from collections import deque
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack1 = deque([])
self.stack2 = deque([])
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.stack1.append(x)
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
l = len(self.stack1)
print(self.stack1)
for i in range(l-1):
self.stack2.append(self.stack1.popleft())
value = self.stack1.popleft()
tmp = self.stack2
self.stack2 = self.stack1
self.stack1 = tmp
# print(self.stack1)
return value
def top(self) -> int:
"""
Get the top element.
"""
return self.stack1[len(self.stack1)-1]
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
if len(self.stack1)==0:
return True
else:
return False
5、用栈实现队列
同理,用栈实现队列,还是要用到两个栈,一个push栈,一个pop栈,主要满足两个基本原则:1、如果往pop栈倒入数据,push栈一定要倒空2、pop栈如果有数据,一定不能从push栈往pop栈放数据。(等于pop栈走了一批再从push栈倒入下一批)题目:https://leetcode-cn.com/problems/implement-queue-using-stacks/
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.pushStack = []
self.popStack = []
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.pushStack.append(x)
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
l = len(self.pushStack)
if self.popStack == []:
for i in range(l):
self.popStack.append(self.pushStack.pop())
return self.popStack.pop()
def peek(self) -> int:
"""
Get the front element.
"""
l = len(self.pushStack)
if self.popStack == []:
for i in range(l):
self.popStack.append(self.pushStack.pop())
return self.popStack[-1]
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
return self.pushStack == [] and self.popStack == []