C语言队列的各项操作

来源:互联网 发布:uefi硬盘安装ubuntu 编辑:程序博客网 时间:2024/05/16 23:41

昨天写了一个队列的操作,结果存在不少问题,心中颇为不爽,遂今天有重新写了一个,暂未发现bug,若有大神发现bug,请指正,谢谢。
这里写图片描述

/*************************************************************************    > File Name: new_queue.c    > Author:heathcliff     > Mail: -------------------     > Created Time: 2016年04月02日 星期六 13时22分48秒 ************************************************************************/#include<stdio.h>#include<stdlib.h>typedef int ElemType;typedef struct node{    ElemType data;    struct node *next;}que_node;struct que{    que_node *front,*rear; //创建队头、队尾指针};int length = 0;//计算队列的长度void init_queue(struct que *q);void enter_queue(struct que *q,ElemType x);ElemType delete_queue(struct que *q);void print(struct que q);int main(void){    struct que *q;    int x,interrupt;    q = (struct que *) malloc (sizeof(struct que));//此步骤必须有,否则会引起程序崩溃    init_queue(q);    printf("\n请输入你想要入对的值,以0结束:");    scanf("%d",&x);    while( x != 0){        enter_queue(q,x);        scanf("%d",&x);    }    print(*q);    printf("length = %d\n",length);    printf("请问是否要出对操作:yes (1),no(0)\n");    scanf("%d",&interrupt);    while(length){        if(interrupt == 1){            x = delete_queue(q);            printf("\n出对元素为:%d",x);            printf("\nlength = %d \n",length);            printf("请问是否继续出对:yes (1),no(0)\n");            scanf("%d",&interrupt);            }        else            exit(0);        }    return 0;}void init_queue(struct que *q){    que_node *head; //创建头指针    head = (que_node *) malloc (sizeof(que_node));    head->next = NULL;    q->rear = head;    q->front = head;}/*入对操作*/void enter_queue(struct que *q ,ElemType x){    que_node *p;    p = (que_node *) malloc (sizeof(que_node));//分配空间    p->data = x;//赋值    /*入对操作在队尾,即rear上进行*/    p->next = NULL;    q->rear->next = p;    q->rear = p;//指针向后移动一位    length ++ ;}/*出对操作*/ElemType delete_queue(struct que *q){    que_node *p;    int keep;    p = (que_node *) malloc (sizeof(que_node));//分配空间    /*出对操作在队头进行,即front*/    if(q->front == q->rear){// 队列为空        printf("队列为空");        keep = 0;    }    else{        p = q->front->next;        q->front->next = p->next;//队头后移一位        if(p->next == NULL)            q->front = q->rear;        keep = p->data ;//保存出对元素的值    }    length -- ;    return keep;}/*打印队列*/void print(struct que q){    que_node *p;    p = (que_node *) malloc (sizeof(que_node));    p = q.front->next;    while(p != NULL){        printf("data = %d\n",p->data);          p = p->next;    }}
1 0
原创粉丝点击