简单实现一个链队列,只有创建队列,进队列,出队列,判断队列空功能。
#include<stdlib.h>
#include<stdio.h>
#define ElemType int
typedef struct Node
{
ElemType data;
struct Node *next;
}QNode;
//This is node of queue
typedef struct Point
{
QNode *front;
QNode *rear;
}qPoint;
//This pointer links the queue
qPoint *InitQuene(); //Initalize a empty quene
qPoint *EnQuene(qPoint *,ElemType ); //insert new rear of queue
qPoint *DeQuene(qPoint *,ElemType *); //delete front of queue,send its data to main
int EmptyQueue(qPoint *); //judge if the queue is empty
void visit(qPoint *);
int main(void)
{
qPoint *queue=InitQuene();
int i=0;
ElemType *data=&i;//must,let this point have initial value
ElemType idata;
int temp;
printf("--|choose operate\n");
printf("--|1.enter queue\n--|2.out queue\n--|3.visit the queue\n--|4.quit\n");
while(1)
{
printf("--|");
scanf("%d",&temp);
if(temp==1)
{
printf("--|please give the data:");
scanf("%d",&idata);
queue=EnQuene(queue,idata);
printf("--|operate success\n");
}
else if(temp==2)
{
if(EmptyQueue(queue))
printf("--|this is a empty queue\n");
else
{
queue=DeQuene(queue,data);
printf("--|operate success,%d out from queue\n",*data);
}
}
else if(temp==3)
{
visit(queue);
}
else if(temp==4)
exit(0);
else
printf("--|errot input\n");
}
return 0;
}
qPoint *InitQuene()
{
qPoint *s=(qPoint *)malloc(sizeof(qPoint));
QNode *temp;
s->front=(QNode *)malloc(sizeof(QNode));
temp=s->front;
temp->data=0;
temp->next=NULL;
s->rear=s->front;
return s;
}
qPoint *EnQuene(qPoint *s,ElemType data)
{
QNode *newnode=(QNode *)malloc(sizeof(QNode));
newnode->next=NULL;
newnode->data=data;
s->rear->next=newnode;//link two nodes
s->rear=newnode;//link point to new node
return s;
}
qPoint *DeQuene(qPoint *s,ElemType *data)
{
QNode *temp=s->front;
*data=s->front->next->data;
s->front=s->front->next;
free(temp);
return s;
}
int EmptyQueue(qPoint *s)
{
if(s->front==s->rear)
return 1;
else
return 0;
}
void visit(qPoint *s)
{
QNode *front_temp,*rear_temp;
front_temp=s->front;
rear_temp=s->rear;
while(front_temp!=rear_temp)
{
front_temp=front_temp->next;
printf("--|%5d|--\n",front_temp->data);
}
}