实现顺序栈和链式栈的基本操作,包括元素的压栈、出栈和访问等; 实现顺序队列、链式队列和循环队列,确保实现正确地处理元素的入队和出队; 用python代码写出来
时间: 2024-11-23 18:40:42 浏览: 10
顺序栈(基于数组实现):
```python
class ArrayStack:
def __init__(self, capacity):
self.capacity = capacity
self.top = -1
self.stack = [None] * capacity
# 压栈(push)
def push(self, item):
if self.is_full():
raise Exception("Stack is full")
self.top += 1
self.stack[self.top] = item
# 出栈(pop)
def pop(self):
if self.is_empty():
raise Exception("Stack is empty")
return self.stack.pop(self.top)
# 访问顶部元素(peek)
def peek(self):
if self.is_empty():
return None
return self.stack[self.top]
# 判断是否为空(is_empty)
def is_empty(self):
return self.top == -1
# 判断是否已满(is_full)
def is_full(self):
return self.top == self.capacity - 1
```
链式栈(基于链表节点实现):
```python
class LinkedStack:
class Node:
def __init__(self, value=None):
self.value = value
self.next = None
def __init__(self):
self.top = None
# ... (其余操作类似,这里省略)
链式队列(基于链表节点实现):
```python
class LinkedListQueue:
class Node:
def __init__(self, value=None):
self.value = value
self.next = None
def __init__(self):
self.front = self.rear = None
# 入队(enqueue)
def enqueue(self, item):
new_node = self.Node(item)
if not self.rear:
self.front = self.rear = new_node
else:
self.rear.next = new_node
self.rear = new_node
# 出队(dequeue)
def dequeue(self):
if not self.front:
raise Exception("Queue is empty")
removed_value = self.front.value
self.front = self.front.next
if not self.front:
self.rear = None
return removed_value
# 循环队列(Circular Queue)
class CircularQueue:
# ... (由于复杂度较高,这里简化示例)
# 同样会有enqueue, dequeue方法,需要维护rear和front指针,并注意边界条件
```
以上代码提供了一个基本框架,实际使用时可能还需要添加错误检查和其他辅助方法。请注意,在实际应用中,循环队列(CircularQueue)会涉及到额外的头指针和尾指针处理以及边界条件。
阅读全文