当前位置: 首页> 科技> 数码 > 单向链表队列

单向链表队列

时间:2025/7/12 7:43:26来源:https://blog.csdn.net/weixin_73503608/article/details/140331955 浏览次数:0次

实现单向链表队列的,创建,入队,出队,遍历,长度,销毁。

 queue.h

#ifndef __QUEUE_H__
#define __QUEUE_H__#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define max 30
typedef int datatype;
typedef struct node
{union{int len;datatype data;};struct node *next;
}node;
typedef struct loop
{node *front;node *tail;
}queue, *queue_p;queue_p create();
int empty(queue_p Q);
int full(queue_p Q);
void add(queue_p Q, datatype num);
void show(queue_p Q);
void pop(queue_p Q);
void lenth(queue_p Q);
void free_queue(queue_p Q);#endif

main.c 

#include "queue.h"int main()
{queue_p Q = create();add(Q, 1);add(Q, 2);add(Q, 3);add(Q, 4);show(Q);pop(Q);show(Q);lenth(Q);free_queue(Q);return 0;
}

queue.c 

#include "queue.h"//创建queue_p create()
{queue_p Q = (queue_p)malloc(sizeof(queue));if(NULL == Q){printf("失败\n");return NULL;}Q -> front  = NULL;Q -> tail = NULL;Q -> front = (node*)malloc(sizeof(node));if(Q -> front == NULL){printf("失败\n");free(Q);Q = NULL;return NULL;}Q -> front -> len = 0;Q -> tail = Q -> front;return Q;}
//判空
int empty(queue_p Q)
{if(NULL == Q){printf("失败");return 0;}return Q -> tail == Q -> front;
}//入队
void add(queue_p Q, datatype data)
{if(NULL == Q){printf("失败\n");return;}node * p = (node *)malloc(sizeof(node));p -> data = data;Q -> tail -> next = p;Q -> tail = p;Q -> front -> len++;}
//遍历
void show(queue_p Q)
{if(NULL == Q || empty(Q)){printf("空\n");return;}printf("队列的元素为:");node *p = Q -> front -> next;do{printf("%d", p -> data);p = p -> next;}while(p != NULL);putchar(10);
}//出队
void pop(queue_p Q)
{if(NULL == Q || empty(Q)){printf("空");return;}node *p = Q -> front -> next;Q -> front -> next = p -> next;if(Q -> front -> next == NULL){Q -> tail = Q -> front;}free(p);p = NULL;Q -> front -> len--;}
//队长
void lenth(queue_p Q)
{if(NULL == Q){printf("失败");return;}printf("队列长度为:%d\n", Q -> front -> len);
}
//销毁
void free_queue(queue_p Q)
{if(NULL == Q){printf("销毁失败\n");return;}while(!empty(Q)){pop(Q);}free(Q -> front);printf("销毁成功\n");
}

实现效果 

关键字:单向链表队列

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: