栈和队列的详细介绍,并且给出代码和图像解释分析原理
时间: 2024-06-09 08:05:04 浏览: 6
栈(Stack)和队列(Queue)是两种常见的数据结构。
## 栈
栈是一种后进先出(LIFO,Last In First Out)的数据结构,类似于一叠盘子,后放入的盘子先被取出。
栈的常见操作有:
- push(item):将元素压入栈顶
- pop():从栈顶取出元素并返回
- peek():返回栈顶元素,但不弹出
- is_empty():判断栈是否为空
- size():返回栈的元素个数
栈的实现可以使用数组或链表。下面是使用数组实现栈的示例代码:
```python
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
```
下图展示了栈的操作过程:
![stack](https://user-images.githubusercontent.com/55041489/132706393-8c1c7d3f-5e3d-4f8d-9f3c-2e4cf1c6c0a4.gif)
## 队列
队列是一种先进先出(FIFO,First In First Out)的数据结构,类似于排队等候,先排队的先被服务。
队列的常见操作有:
- enqueue(item):将元素加入队尾
- dequeue():弹出队首元素并返回
- is_empty():判断队列是否为空
- size():返回队列的元素个数
队列的实现一般使用链表,因为使用数组实现会涉及到元素移动的问题。下面是使用链表实现队列的示例代码:
```python
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Queue:
def __init__(self):
self.head = None
self.tail = None
def enqueue(self, item):
node = Node(item)
if self.tail:
self.tail.next = node
else:
self.head = node
self.tail = node
def dequeue(self):
if not self.head:
raise Exception("Queue is empty")
node = self.head
self.head = node.next
if not self.head:
self.tail = None
return node.value
def is_empty(self):
return self.head is None
def size(self):
size = 0
node = self.head
while node:
size += 1
node = node.next
return size
```
下图展示了队列的操作过程:
![queue](https://user-images.githubusercontent.com/55041489/132706411-3f3c1a3a-2c47-4c6f-8a0b-7dfb6c4a86af.gif)
总结:栈和队列是两种常用的数据结构,它们具有不同的操作方式和实现方式,可以根据具体的需求选择合适的数据结构。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)