队列的实现用链表来实现,两个结构体,一个是节点,一个用于控制队列,有插入节点、删除节点、输出队列几个功能
P.S: fflush(stdin)在VC可以用,GCC不行,可以写几句代码来代替~
代码/* implement a queue
* functions:insert,delete,print
*/
#include <stdio.h>
#include <stdlib.h>
struct node{ //nodes of queue
int key;
struct node *next;
};
typedef struct node Node;
struct qu{ //the controller of the queue
Node *front;
Node *rear;
};
typedef struct qu Queue;
Queue *init_queue(Queue *Q)
{
Q=(Queue *)malloc(sizeof(Queue));
if(NULL == Q){
printf("Mlloc error!\n");
exit(1);
}
Q->front=Q->rear=NULL;
return Q;
}
void enQueue(Queue *Q,int data)
{
Node *temp;
temp=(Node *)malloc(sizeof(Node));
if(NULL == temp){
printf("Malloc error!\n");
exit(1);
}
temp->key=data;
temp->next=NULL;
if(NULL == Q->rear){//the queue is empty
Q->front=Q->rear=temp;
}else{
Q->rear->next=temp;
Q->rear=temp;
}
}
void deQueue(Queue *Q)
{
Node *p;
if(NULL == Q->front){
printf("Empty!\n");
return;
}
if(Q->front == Q->rear){//delete the latest node
Q->rear=NULL;
}
p=Q->front;
Q->front=Q->front->next;
printf("Delet date:%d \n",p->key);
free(p);
}
void print_queue(Queue *Q)
{
Node *p=Q->front;
if(NULL == p){
printf("The queue is empty!\n");
return;
}
while(p){
printf("%d ",p->key);
p=p->next;
}
printf("\n");
}
int main(int argc,char **argv)
{
int data;
char e;
Queue *Q=NULL;
Q=init_queue(Q);
while(1){
fflush(stdin);
printf("Input the operator(i-insert,d-delete,p-print,q-quit):");
scanf("%c",&e);
switch(e){
case 'i':
fflush(stdin);
printf("Input a number:");
scanf("%d",&data);
enQueue(Q,data);
break;
case 'd':
deQueue(Q);
break;
case 'p':
print_queue(Q);
break;
case 'q':
return 0;
break;
default:
printf("Unknown Operator!\n");
}
}
return 0;
}
|
阅读(789) | 评论(0) | 转发(0) |