一个小菜鸡对链队的学习
老师还没教到数据结构,大一就先自学了。
初看链队,看网上的图示觉得概念还是很简单的。但是看源码的时候还是有点晕的。在后面慢慢看,终是看懂了。下面用链队实现一些基本的功能,同时在下面加一下自己的理解。
首先是标记队头和队尾的指针是不同与以往的指针,这个指针是一个指向结构体的指针。
指向结构体的指针
先定义链队的节点
struct queueNode
{
int data;
struct queueNodenext;
};
再定义链队的指向队头队尾的指针
struct linkNode
{
struct queueNodefront;//队头指针
struct queueNoderear;//队尾指针
};
接着先初始化
struct linkNodecreatqueue()
{
struct linkNodeque=(struct linkNode)malloc(sizeof (struct linkNode));
que->front=(struct queueNode*)malloc(sizeof(struct queueNode));
que->front->data=0;
que->front->next=NULL;//避免野指针
que->rear=que->front;
//让头指针和尾指针指向同一点表示队列为空(顺序不能反否则会报错)
return que;
}
入队操作
void enterqueue(struct linkNodeque,int value)
//接受的指针都是指向队头的指针,不是连接链队节点的指针
{
struct queueNodepnew=(struct queueNode*)malloc(sizeof(struct queueNode));
//创立节点用来连接
pnew->data=value;
pnew->NULL;//没有这步打印时可能会报错
que->rear->next=pnew;
que->rear=que->rear->next;//用尾指针连接,头指针不动
}
//出队操作
void outqueueNode(struct linkNodeque)
{
struct queueNodep=que->front->next;//指针p指向队头的第二个元素
p->front->next=p->next;//摘掉第二个元素
free§;//释放空间
p=NULL;//指向空避免出现野指针
}
//打印操作
void print(struct linkNodeque)
{
struct queueNodeprt=que->front->next;
//跳过队头(队头元素的值为0,所以打印的时候没打印)
while(prt!=NULL)
{
printf("%d",prt->datat);
prt=prt->next;
}
}
参考链接: https://www.cnblogs.com/electronic/p/10896510.html
int main()
{
struct linkNode* que = creat();
enterqueue(que, 1);
enterqueue(que, 2);
enterqueue(que, 3);
enterqueue(que, 4);
enterqueue(que, 5);
enterqueue(que, 6);
outqueueNode(que);
outqueueNode(que);
show(que);
return 0;
}