2008秋季-计算机软件基础-0922课堂用例(2)
  TnD0WQEygW8e 2023年11月09日 192 0
/*---------------------------------------------------------

 Title: Link Queue(链队列) 链队列-链式存储结构的队列 

  请先阅读教材74-77页, 2.4.1-2.4.4节, 队列的定义及基本运算

 (注意:以下程序为简化后的,仅供入门学习之用)

----------------------------------------------------------*/

#include<stdio.h>

#include<stdlib.h>
//定义队列的结构
struct queueNode

{

   int data;//存放数据元素
   struct queueNode * next;//指针,指向下一个结点
};
struct queue

{

    struct queueNode * front;

    struct queueNode * rear;

};

//初始化队列
struct queue * InitialQueue()

{

 struct queue * head;

 struct queueNode * node;

 node=(struct queueNode *)malloc(sizeof(struct queueNode ));

 head=(struct queue *)malloc(sizeof(struct queue ));

 node->next=NULL;

 head->front=node;

 head->rear=node;

 return head;

}

//入队列
void EnterIntoQueue(struct queue * head, int value)

{

    struct queueNode * node;

    node=(struct queueNode *)malloc(sizeof(struct queueNode ));

    node->data=value;

    node->next=NULL;

    head->rear->next=node;

    head->rear=node;

    

 }

//出队列
void DeleteFromQueue(struct queue * head)

{

    struct queueNode * node;

 if(head->front==head->rear)

 {

     printf("Queue is empty, Delete failed\n");

 }

 else

    {

    node=head->front->next;

    head->front->next=node->next;

    free(node);

    // when there is only one element, the following is necessary.
     if(head->front->next==NULL)

     head->rear=head->front;

    }

}

//显示队列中所有元素
void ShowAllElements(struct queue * head)

{

 struct queueNode * node;

 printf("\n Show all elements: \n");

 node=head->front->next;

 while(node!=NULL)

 {

  printf(" %d ",node->data);

  node=node->next;

 }

}

void main()

{

    struct queue * head1;

    head1=InitialQueue();


    ShowAllElements(head1);

    EnterIntoQueue(head1,11);

    ShowAllElements(head1);

    EnterIntoQueue(head1,22);

    ShowAllElements(head1);

    DeleteFromQueue(head1);

    ShowAllElements(head1);

}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月09日 0

暂无评论

推荐阅读
TnD0WQEygW8e