数据结构C语言实现系列——队列

来源:互联网 发布:java编程思想新版 编辑:程序博客网 时间:2024/06/06 04:53
// test.cpp : 定義主控台應用程式的進入點。//#include "stdafx.h"#include <stdio.h>#include <stdlib.h>typedef int elemType;/************************************************************************//*                    以下是关于队列链接存储操作的6种算法               *//************************************************************************/typedef struct s_Node{    elemType data;            /* 值域 */    struct s_Node *next;        /* 链接指针 */}sNode;struct queueLK{    sNode *front;    /* 队首指针 */    sNode *rear;        /* 队尾指针 */};/* 1.初始化链队 */void initQueue(struct queueLK *hq){    hq->front = hq->rear = NULL;        /* 把队首和队尾指针置空 */    return;}/* 2.向链队中插入一个元素x */void enQueue(struct queueLK *hq, elemType x){sNode *new_node;new_node=(sNode *)malloc(sizeof(sNode));if(new_node==NULL){printf("Malloc memory failed!\n");return;}new_node->data=x;new_node->next=NULL;if(hq->rear==NULL) //空链表{hq->front=hq->rear=new_node;}else{hq->rear->next=new_node;hq->rear=new_node;}}/* 3.从队列中删除一个元素 */elemType outQueue(struct queueLK *hq){sNode *p;elemType temp;if(hq->front==NULL){printf("Null queue!\n");return -1;}else{p=hq->front;   //第一个元素temp=hq->front->data;hq->front=hq->front->next;if(hq->front==NULL)hq->rear=NULL;free(p);}return temp;}/* 4.读取队首元素 */elemType peekQueue(struct queueLK *hq){if(hq->front==hq->rear){printf("Null queue!\n");return -1;}return hq->front->data;}/* 5.检查链队是否为空,若为空则返回1, 否则返回0 */int emptyQueue(struct queueLK *hq){if(hq->front==hq->rear)return 1;elsereturn 0;}/* 6.清除链队中的所有元素 */void clearQueue(struct queueLK *hq){sNode *p;p=hq->front;while(p!=NULL){hq->front=hq->front->next;free(p);p=hq->front;}hq->rear=NULL;}int main(){int a[10] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};int b[5] = {4,5,6,7,8};    int i;struct queueLK myQueue;initQueue(&myQueue);for(i = 0; i < 8; i++){        enQueue(&myQueue, a[i]);    }printf("删除一个元素=%d\n",outQueue(&myQueue));printf("第一个元素=%d\n",peekQueue(&myQueue));while(1);}


原创粉丝点击