您的位置:首页 > 移动开发 > 微信开发

每天一个小程序(9)——链队

2014-03-24 10:48 288 查看
#include <stdio.h>
#include <stdlib.h>

typedef int datatype;
typedef struct node
{
datatype data;
struct node *next;
}QNode;
typedef struct
{
QNode *front,*rear;
}LQueue;

//链队

//初始化
LQueue* Init_LQueue()
{
LQueue* q;
QNode *p;
q = (LQueue*)malloc(sizeof(LQueue));
p = (QNode*)malloc(sizeof(QNode));
p->next = NULL;
q->front = q->rear = p;
return q;
}
//入队
void In_LQueue(LQueue* q,datatype x)
{
QNode* p;
p = (QNode*)malloc(sizeof(QNode));
p->data = x;
p->next = NULL;
q->rear->next = p;//将p连接到尾部
q->rear = p;//使rear指向新的尾部
}
//判队空
int Empty_LQueue(LQueue* q)
{
if(q->front == q->rear)
return 1;
else
return 0;
}
//出队
int Out_LQueue(LQueue* q,datatype *x)
{
QNode* p;
if(Empty_LQueue(q))
return 0;
else
{
p = q->front->next;//将队头的第一个元素赋予p
q->front->next = p->next;//将第二个元素放在队头的next
*x = p->data;
free(p);
if(q->front->next == NULL)
q->rear = q->front;
return 1;
}
}

void main()
{
LQueue* q = Init_LQueue();
int data;
printf("入队:\n");
scanf("%d",&data);
while(data != -1)
{
In_LQueue(q,data);
scanf("%d",&data);
}
printf("\n出队:\n");
while(Out_LQueue(q,&data))
{
printf("%d ",data);
}
printf("\n");
}




小结

队列是限定仅能在表尾一端进行插入,表头一端进行删除操作的线性表;

队列中的元素具有先进先出的特点;

队头、队尾元素的位置分别由称为队头指针和队尾指 针的变量指示。

入队操作要修改队尾指针,出队操作要修改队头指针。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: