原文链接:点击打开链接
用栈实现下列队列操作:
- push(x) 在队列末尾添加元素x
- pop() 删除队列首的元素
- peek() 返回队列首元素但不删除它
- empty() 判断队列是否为空
struct Queue {
int data;
struct Queue* next;
};
typedef struct Queue Queue;
/* Create a queue */
void queueCreate(Queue *queue, int maxSize) {
queue = (Queue*)malloc(sizeof(Queue));
queue->next = NULL;
Queue* end_of_queue = queue;
while (maxSize--) {
int data_in_node;
Queue* q = (Queue*)malloc(sizeof(Queue));
if (NULL == q)
break;
printf("Please input the data of this node: ");
scanf("%d", &data_in_node);
q->next = end_of_queue->next;
q->data = data_in_node;
end_of_queue->next = q;
end_of_queue = q;
}
}
/* Push element x to the back of queue */
void queuePush(Queue *queue, int element) {
Queue* q = (Queue*)malloc(sizeof(Queue));
if (NULL == q)
return ;
Queue* end = queue->next;
while (NULL != end->next)
end = end->next;
q->next = end->next;
end->next = q;
}
/* Removes the element from front of queue */
void queuePop(Queue *queue) {
if (NULL == queue->next)
return;
Queue* top = queue->next;
queue->next = top->next;
free(top);
}
/* Get the front element */
int queuePeek(Queue *queue) {
if (NULL == queue->next)
return -1;
return (queue->next->data);
}
/* Return whether the queue is empty */
bool queueEmpty(Queue *queue) {
return (NULL == queue->next);
}
/* Destroy the queue */
void queueDestroy(Queue *queue) {
if (NULL == queue->next)
return ;
Queue* ds = queue->next;
Queue* dsNext = ds->next;
while (NULL != dsNext->next) {
free(ds);
ds = dsNext;
dsNext = dsNext->next;
}
free(dsNext);
queue->next = NULL;
}