链式队列的实现

/*链式队列其实就是一种特殊的单链表
只要单链表和结构体的知识咂实
就能很轻松的实现*/

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
static int c=0;
typedef struct node
{
int data;
struct node *next;
}lnode,*queue;
typedef struct qnode
{
queue front;
queue rear;
}pnode,*queue1;

queue1 init()
{ queue1 l;
l=(pnode *)malloc(sizeof(pnode));
queue p;
p=(lnode *)malloc(sizeof(lnode));
if(p==NULL)
{
printf("内存分配失败");
exit(-1);
}
else
{ p->next=NULL;
l->front=p;
l->rear=p;
}
return l;
}

int push(pnode *l,int n)
{
lnode *p;
p=(lnode*)malloc(sizeof(lnode));
if(p==NULL)
{
printf("内存分配失败");
exit(-1);
}
else
{ p->next=NULL;
p->data=n;
c++;
l->rear->next=p;
l->rear=p;
}
return 1;
}

int del(pnode *l,int *n)
{
lnode *p,*s;

if(l->front==l->rear)
{
printf("empty");
return 0;
}
else
{
p=l->front->next;
l->front->next=p->next;
*n=p->data;

free(p);
c--;
// if(l->front->next==NULL)
// l->rear=l->front;
return *n;
}

}

void tra(queue1 l)
{
queue p,q,s;
p=l->front;
q=l->rear;
s=p->next;
printf("队列的值:");
for(int i=0;i<c;i++)
{
printf("%d ",s->data);
s=s->next;
}
}
int main()
{ pnode *l;
int n;
l=init();
push(l,1);
push(l,2);
push(l,3);
push(l,4);
push(l,5);
tra(l);
printf("\n");
del(l,&n);
printf("出列的数 :%d\n",n);
printf("\n");
tra(l);
return 0;
}

posted @ 2016-09-15 02:22  mykonons  阅读(185)  评论(0编辑  收藏  举报