链表的队列实现:
需要注意两个点:
1)front和rear 是一个单独的不分配数据的结点,它的实际结点是下一个,不是当前的!
2)每次入队列的时候,需要分配一个结点,不然会core segment error!
#include<stdio.h>
#include<stdlib.h>
typedef struct LinkList
{
int data;
struct LinkList *next;
}LinkNode,*pLinkList;
typedef struct queue
{
pLinkList front;
pLinkList rear;
}Queue;
void InitQueue(Queue *p);
int isEmpty(Queue *p);
void EnQueue(Queue *p,int num);
void Dequeue(Queue *p,int *num);
void InitQueue(Queue *p)
{
p->front = (pLinkList)malloc(sizeof(struct LinkList));
p->rear = p->front;
}
int isEmpty(Queue *p)
{
if(p->front == p->rear) return 1;
return 0;
}
void EnQueue(Queue *p,int num)
{
if(p==NULL) printf("p is null\n");
pLinkList s;
s = (pLinkList)malloc(sizeof(struct LinkList));
s->data = num;
s->next = NULL;
p->rear->next = s;
p->rear = s;
}
void Dequeue(Queue *p,int *num)
{
if(isEmpty(p)) printf("Queue is empty\n");
*num = p->front->next->data;
pLinkList s;
s = p->front->next;
p->front = s->next;
free(s);
}
int main()
{
Queue head;
InitQueue(&head);
EnQueue(&head,7);
EnQueue(&head,8);
EnQueue(&head,9);
int num;
Dequeue(&head,&num);
printf("Dequeue num = %d\n",num);
return 0;
}