实现单向链表队列的,创建,入队,出队,遍历,长度,销毁。
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");
}
实现效果