数据结构:链队列

链队列其实就是对单链表进行先进先出操作
front和rear刚开始都指向phead,每次添加元素就创建新的结点,rear指向最新的结点

#include<stdio.h>
#include<malloc.h>

typedef struct node
{
	int data;
	struct node* next;
}node, * nodeptr;

typedef struct queue
{
	nodeptr front, rear;
}queue,*queueptr;

//链队列其实就是对单链表进行先进先出操作

queueptr creat()
{
	nodeptr phead = (nodeptr)malloc(sizeof(node));
	queueptr p = (queueptr)malloc(sizeof(queue));
	phead->next = NULL;
	p->front = phead;
	p->rear = phead;
	return p;
	//返回队列的地址,而不是首结点的地址
	//因为返回队列地址可以得到首结点地址,而返回首结点地址不能得到队列的地址
}

void insert(queueptr p,int ele)
{
	nodeptr pnew = (nodeptr)malloc(sizeof(node));
	pnew->data = ele;
	pnew->next = NULL;
	p->rear->next = pnew;//让rear此时所指向的结点的next指向新的结点
	p->rear = pnew;//让rear指向新构建的结点
}

void print(queueptr p)
{
	nodeptr p1 = p->front; int flag = 0;
	while (p1->next != NULL)
	{
		p1 = p1->next;
		printf("%d", p1->data);
		flag = 1;
	}
	if (flag == 1)
	{
		printf("\n");
	}
	else
	{
		printf("the queue is empty\n");
	}
}

void deleteelement(queueptr p)
{	
	nodeptr p2 = p->front->next;
	if (p2 == NULL)
	{
		printf("fail to delete cause the queue is already empty\n");
		return;
	}
	p->front->next= p->front->next->next;
	free(p2);
}
//front指向的一直是phead
//free掉phead->next指向的node

int main()
{
	queueptr p = creat(); int i;
	for (i = 0; i < 5; i++)
	{
		insert(p, i);
		print(p);
	}
	for (i = 0; i < 5; i++)
	{
		deleteelement(p);
		print(p);
	}
	deleteelement(p);
	print(p);
}

运行结果:

0
01
012
0123
01234
1234
234
34
4
the queue is empty
fail to delete cause the queue is already empty
the queue is empty
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值