(1)采用链式存储实现栈的初始化、入栈、出栈操作。(2)采用顺序存储实现栈的初始化、入栈、出栈操作。 (3)采用链式存储实现队列的初始化、入队、出队操作。 (4)采用顺序存储实现循环队列的初始化、入队、出队操作。(5)在主函数中设计一个简单的菜单,分别测试上述算法。
时间: 2023-11-04 10:06:07 浏览: 107
采用顺序存储实现栈的初始化、入栈、出栈操作
1. 链式存储实现栈的初始化、入栈、出栈操作
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.top = None
def is_empty(self):
return self.top is None
def push(self, data):
node = Node(data)
node.next = self.top
self.top = node
def pop(self):
if self.is_empty():
return None
data = self.top.data
self.top = self.top.next
return data
```
2. 顺序存储实现栈的初始化、入栈、出栈操作
```python
class Stack:
def __init__(self):
self.data = []
def is_empty(self):
return len(self.data) == 0
def push(self, data):
self.data.append(data)
def pop(self):
if self.is_empty():
return None
return self.data.pop()
```
3. 链式存储实现队列的初始化、入队、出队操作
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.front = None
self.rear = None
def is_empty(self):
return self.front is None
def enqueue(self, data):
node = Node(data)
if self.is_empty():
self.front = node
self.rear = node
else:
self.rear.next = node
self.rear = node
def dequeue(self):
if self.is_empty():
return None
data = self.front.data
self.front = self.front.next
if self.front is None:
self.rear = None
return data
```
4. 顺序存储实现循环队列的初始化、入队、出队操作
```python
class Queue:
def __init__(self, size):
self.data = [None] * size
self.front = 0
self.rear = 0
self.size = size
def is_empty(self):
return self.front == self.rear
def is_full(self):
return (self.rear + 1) % self.size == self.front
def enqueue(self, data):
if self.is_full():
return False
self.data[self.rear] = data
self.rear = (self.rear + 1) % self.size
return True
def dequeue(self):
if self.is_empty():
return None
data = self.data[self.front]
self.front = (self.front + 1) % self.size
return data
```
5. 主函数中的菜单
```python
def main():
stack = Stack()
queue = Queue()
while True:
print("1. Push to stack")
print("2. Pop from stack")
print("3. Enqueue to queue")
print("4. Dequeue from queue")
print("0. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
data = input("Enter data: ")
stack.push(data)
elif choice == 2:
data = stack.pop()
if data is None:
print("Stack is empty")
else:
print("Popped data:", data)
elif choice == 3:
data = input("Enter data: ")
queue.enqueue(data)
elif choice == 4:
data = queue.dequeue()
if data is None:
print("Queue is empty")
else:
print("Dequeued data:", data)
elif choice == 0:
break
else:
print("Invalid choice")
```
阅读全文