您的位置:首页 > 理论基础 > 数据结构算法

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

2012-07-08 21:43 555 查看
// 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;
else
return 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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: