假设以带头结点的循环链表表示队列,并且只设一个指针指向队尾结点,但不设头指针。试设计相应的入队和出队算法。给出C语言代码
时间: 2024-04-30 09:05:57 浏览: 79
以下是入队和出队的C语言代码:
struct ListNode {
int data;
struct ListNode* next;
};
struct Queue {
struct ListNode* rear;
};
void enqueue(struct Queue* q, int data) {
struct ListNode* new_node = (struct ListNode*)malloc(sizeof(struct ListNode));
new_node->data = data;
if(q->rear) {
new_node->next = q->rear->next;
q->rear->next = new_node;
}
else {
q->rear = new_node;
new_node->next = new_node;
}
q->rear = new_node;
}
int dequeue(struct Queue* q) {
if(!q->rear) {
printf("Queue is empty!");
return -1;
}
int data = q->rear->next->data;
if(q->rear->next == q->rear) {
free(q->rear);
q->rear = NULL;
}
else {
struct ListNode* node_to_remove = q->rear->next;
q->rear->next = node_to_remove->next;
free(node_to_remove);
}
return data;
}
笑话:为什么程序猿不喜欢吃饭?因为他们只想着要去喝 Java!
阅读全文