数据结构day6链式队列

主程序

#include "fun.h"

int main(int argc, const char *argv[])

{

que_p Q=create();

enqueue(Q,10);

enqueue(Q,20);

enqueue(Q,30);

enqueue(Q,40);

enqueue(Q,50);

show_que(Q);

dequeue(Q);

show_que(Q);

printf("len:%d\n",que_len(Q));

free_que(Q);

Q=NULL;

show_que(Q);

return 0;

}

源程序

#include "fun.h"

que_p create()

{

que_p Q=(que_p)malloc(sizeof(que));

if(Q==NULL)

{

printf("error\n");

return NULL;

}

node_p H=(node_p)malloc(sizeof(node));

if(H==NULL)

{

printf("error\n");

free(Q);

Q=NULL;

return NULL;

}

H->next=NULL;

H->len=0;

Q->head=H;

Q->tail=H;

return Q;

}

int empty_que(que_p Q)

{

if(Q==NULL)

{

printf("error\n");

return -1;

}

return Q->head==Q->tail;

}

node_p create_new(typdata data)

{

node_p new =(node_p)malloc(sizeof(node));

if(new==NULL)

{

printf("error");

}

new->data=data;

new->next=NULL;

return new;

}

void enqueue(que_p Q,typdata data)

{

if(Q==NULL)

{

printf("erro\n");

}

node_p new=create_new(data);

Q->tail->next=new;

Q->tail=new;

Q->head->len++;

}

void show_que(que_p Q)

{

if(Q==NULL)

{

printf("error\n");

return;

}

if(empty_que(Q))

{

printf("Queue empty\n");

return;

}

node_p H=Q->head;

while(H->next!=NULL)

{

H=H->next;

printf("%-4d",H->data);

}

putchar(10);

}

void dequeue(que_p Q)

{

if(Q==NULL)

{

printf("error\n");

return;

}

if(empty_que(Q))

{

printf("Queue empty\n");

return;

}

printf("dequeue:%d\n",Q->head->next->data);

node_p p=Q->head->next;

Q->head->next=Q->head->next->next;

free(p);

p=NULL;

Q->head->len--;

}

int que_len(que_p Q)

{

if(Q==NULL)

{

printf("error\n");

return-1;

}

return Q->head->len;

}

void free_que(que_p Q)

{

if(Q==NULL)

{

printf("error\n");

return;

}

while(Q->head->next!=NULL)

{

dequeue(Q);

}

free(Q->head);

Q->head=NULL;

free(Q);

Q=NULL;

}

头文件

#ifndef _FUN_H

#define _FUN_H

#include <myhead.h>

typedef int typdata;

typedef struct node

{

union

{

int len;

typdata data;

};

struct node *next;

}node,*node_p;

typedef struct queue

{

node_p head;

node_p tail;

}que,*que_p;

que_p create();

int empty_que(que_p Q);

node_p create_new(typdata data);

void enqueue(que_p Q,typdata data);

void show_que(que_p Q);

void dequeue(que_p Q);

int que_len(que_p Q);

void free_que(que_p Q);

#endif

相关推荐
小明说Java2 分钟前
常见排序算法的实现
数据结构·算法·排序算法
小熳芋5 小时前
验证二叉搜索树- python-递归&上下界约束
数据结构
不穿格子的程序员8 小时前
从零开始写算法——链表篇2:从“回文”到“环形”——链表双指针技巧的深度解析
数据结构·算法·链表·回文链表·环形链表
诺....9 小时前
C语言不确定循环会影响输入输出缓冲区的刷新
c语言·数据结构·算法
长安er10 小时前
LeetCode876/141/142/143 快慢指针应用:链表中间 / 环形 / 重排问题
数据结构·算法·leetcode·链表·双指针·环形链表
workflower11 小时前
PostgreSQL 数据库的典型操作
数据结构·数据库·oracle·数据库开发·时序数据库
仰泳的熊猫11 小时前
1140 Look-and-say Sequence
数据结构·c++·算法·pat考试
EXtreme3511 小时前
栈与队列的“跨界”对话:如何用双队列完美模拟栈的LIFO特性?
c语言·数据结构·leetcode·双队列模拟栈·算法思维
松涛和鸣11 小时前
29、Linux进程核心概念与编程实战:fork/getpid全解析
linux·运维·服务器·网络·数据结构·哈希算法