用C语言写一个链队列实现银行取钱模拟
时间: 2023-04-06 10:04:34 浏览: 96
好的,我可以回答这个问题。以下是用C语言写一个链队列实现银行取钱模拟的代码:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
typedef struct queue {
Node *front;
Node *rear;
} Queue;
void initQueue(Queue *q) {
q->front = q->rear = (Node *)malloc(sizeof(Node));
q->front->next = NULL;
}
int isEmpty(Queue *q) {
return q->front == q->rear;
}
void enQueue(Queue *q, int data) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
q->rear->next = newNode;
q->rear = newNode;
}
int deQueue(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty!\n");
return -1;
}
Node *temp = q->front->next;
int data = temp->data;
q->front->next = temp->next;
if (q->rear == temp) {
q->rear = q->front;
}
free(temp);
return data;
}
int main() {
Queue q;
initQueue(&q);
int choice, amount;
do {
printf("1. Deposit\n");
printf("2. Withdraw\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter amount to deposit: ");
scanf("%d", &amount);
enQueue(&q, amount);
printf("Amount deposited: %d\n", amount);
break;
case 2:
printf("Enter amount to withdraw: ");
scanf("%d", &amount);
if (isEmpty(&q)) {
printf("No money in the bank!\n");
} else if (amount > q.front->next->data) {
printf("Not enough money in the bank!\n");
} else {
int remaining = deQueue(&q) - amount;
if (remaining > 0) {
enQueue(&q, remaining);
}
printf("Amount withdrawn: %d\n", amount);
}
break;
case 3:
printf("Exiting...\n");
break;
default:
printf("Invalid choice!\n");
}
} while (choice != 3);
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)