链式队列实现:
1.创建一个空队列
2.尾插法入队
3.头删法出队
4.遍历队列
一、main函数
#include <stdio.h> #include "./3.linkqueue.h" int main(int argc, const char *argv[]) { linkpos* pos = create_linkqueue(); show_linkqueue(pos);insertENd_linkqueue(pos,111); insertENd_linkqueue(pos,222); insertENd_linkqueue(pos,333); insertENd_linkqueue(pos,444); insertENd_linkqueue(pos,555); show_linkqueue(pos); dataType num = output_linkqueue(pos); printf("出队的数据为:%d\n",num); show_linkqueue(pos); return 0; }
二、功能函数
#include <stdio.h>
#include <stdlib.h>
#include "./3.linkqueue.h" //创建
linkpos* create_linkqueue()
{ linkpos* pos = (linkpos*)malloc(sizeof(linkpos)); pos->front = (linkqueue*)malloc(sizeof(linkqueue)); if(NULL == pos->front) { printf("队列创建失败\n"); return NULL; } pos->front->next =NULL; pos->rear = pos->front; pos->front->text.len = 0; return pos;
} //判空
int isEmpty_linkqueue(linkpos*pos)
{ return pos->front == pos->rear?1:0;
} //遍历
void show_linkqueue(linkpos*pos)
{ if(isEmpty_linkqueue(pos)) { printf("队列为空!\n"); return ; } linkqueue* p = pos->front->next; while(p != pos->rear) { printf("%d ",p->text.data); p=p->next; } printf("\n"); return ;
} //尾插 入队
void insertENd_linkqueue(linkpos*pos,dataType num)
{ linkqueue* temp = (linkqueue*)malloc(sizeof(linkqueue)); if(NULL == temp) { printf("结点创建失败,入队失败\n"); return; } temp->next = NULL; temp->text.data = num; temp->next = pos->rear->next; pos->rear->next = temp; pos->rear = pos->rear->next; pos->front->text.len++; return; } //头删 出队
dataType output_linkqueue(linkpos*pos)
{ if(isEmpty_linkqueue(pos)) { printf("队列为空,无法出队\n"); return (dataType)-1; } linkqueue* temp; temp = pos->front->next; pos->front->next = temp->next; dataType num =temp->text.data; if(pos->front->next == NULL) {pos->rear = pos->front;} free(temp); return num;
}
三、头文件
#ifndef __LINKQUEUE_H__#define __LINKQUEUE_H__typedef int dataType;union msg{dataType data;int len;};typedef struct node{union msg text;struct node* next;}linkqueue;typedef struct{linkqueue* front;linkqueue* rear;}linkpos;linkpos* create_linkqueue();void insertENd_linkqueue(linkpos*pos,dataType num);dataType output_linkqueue(linkpos*pos);void show_linkqueue(linkpos*pos); #endif