/*
单链表实现的队列,先进先出
*/
# include
# include
//节点类型
typedef struct node
{
int data;
struct node * pNext;
}NODE, * PNODE;
//队列类型
typedef struct link_queue
{
PNODE front; //指向链表队列的头结点
PNODE rear; //指向链表队列的尾节点
}queue;
void inital(queue &q);
void inQ(queue &q, int i);
void outQ(queue &q ,int * val);
int main(void)
{
int len;
int val;
int i;
//队列初始化
queue q;
inital(q);
printf("请输入要入队的元素个数:len = ");
scanf("%d", &len);
for(i = 0; i < len; i++)
{
printf("第%d个入列元素 val = ", i+1);
scanf("%d", &val);
inQ(q, val);
}
printf("元素出列:");
for(i = 0; i < len; i++)
{
outQ(q, &val);
printf("%d ", val);
}
printf("\n");
return 0;
}
//初始化队列
void inital(queue &q)
{
q.front = (PNODE)malloc(sizeof(NODE)); //头结点
q.front->pNext = NULL;
q.rear = q.front; //尾节点
}
//元素入栈,在链尾添加元素
void inQ(queue &q, int i)
{
//开辟新节点
PNODE pNew = (PNODE)malloc(sizeof(NODE));
pNew->data = i;
pNew->pNext = NULL;
q.rear->pNext = pNew; //新节点挂在链尾
q.rear = pNew;
}
//元素出栈,删除首节点
void outQ(queue &q ,int * val)
{
PNODE p = q.front->pNext;
* val = p->data;
q.front->pNext = p->pNext;
free(p);
}