链队列银行排队叫号系统,模拟银行客户排队办理业务的过程:通过取号进队、排队等候、叫号服务、当前不排队,余下依次等待、下班等
时间: 2023-05-27 15:04:12 浏览: 155
银行客户排队等候系统模拟
4星 · 用户满意度95%
待状态。具体实现如下:
```python
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class Queue:
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def is_empty(self):
return self.size == 0
def enqueue(self, data):
node = Node(data=data)
if self.tail is None:
self.head = node
else:
self.tail.next = node
self.tail = node
self.size += 1
def dequeue(self):
if self.is_empty():
raise Exception("Queue is empty")
data = self.head.data
self.head = self.head.next
self.size -= 1
if self.is_empty():
self.tail = None
return data
class BankQueue:
def __init__(self):
self.queue = Queue()
self.current_num = 0
self.max_num = 99
def get_number(self):
if self.current_num > self.max_num:
raise Exception("Bank is closed")
self.current_num += 1
return self.current_num
def enqueue_customer(self):
number = self.get_number()
self.queue.enqueue(number)
def serve_customer(self):
return self.queue.dequeue()
bank = BankQueue()
for i in range(10):
bank.enqueue_customer()
for i in range(4):
print(f"Serving customer {bank.serve_customer()}")
for i in range(6):
bank.enqueue_customer()
print(f"Next customer to serve is {bank.serve_customer()}")
```
在上述代码中,我们定义了一个 `Queue` 类来实现链队列,然后定义了一个 `BankQueue` 类来实现银行排队叫号系统。在 `BankQueue` 类中,我们定义了一个 `get_number` 方法来获取一个新的号码,它从 1 开始,直到 99,然后抛出异常表示银行已经关闭。我们还定义了 `enqueue_customer` 方法来将新客户入队,以及 `serve_customer` 方法来服务下一个客户。
在主函数中,我们首先让 10 个客户进入队列,然后依次服务前 4 个客户,然后让另外 6 个客户进入队列,最后服务下一个客户。输出如下:
```
Serving customer 1
Serving customer 2
Serving customer 3
Serving customer 4
Next customer to serve is 5
```
阅读全文