您的位置:首页 > 编程语言 > C语言/C++

C语言实现链式队列

2013-10-16 21:12 411 查看
C语言实现,只是简单实现了初始化、入队、出队和打印四个功能比较简单。

#include<stdio.h>
#include<stdlib.h>

typedef int elemType;

typedef struct qNode{
elemType info;
struct qNode *next;
}qNode;

typedef struct{
qNode *front;
qNode *rear;
}LinkQueue;

void initQueue(LinkQueue *q){
//	q->front = q->rear = (qNode *)malloc(sizeof(qNode));
//	q->front->next = NULL;
q->front = q->rear = NULL;
}

void enQueue(LinkQueue *q, elemType value){
qNode *ptr;
ptr = (qNode *)malloc(sizeof(qNode));
ptr->info = value;
ptr->next = NULL;
if(q->front == NULL ){
q->front = ptr;
q->rear = ptr;
}
else{
q->rear->next = ptr;
q->rear = ptr;
}
}

int deQueue(LinkQueue *q){
qNode *ptr = q->front;
if(q->front != NULL){
if(ptr != q->rear)
q->front = ptr->next;
else
q->front = q->rear = NULL;
free(ptr);
return 0;
}
printf("empty queue !\n");
return -1;
}

void printQueue(LinkQueue *q){
qNode *ptr = q->front;
if(ptr == q->rear && ptr == NULL)
return ;
if(ptr != NULL && q->front == q->rear){
printf("%d\n",ptr->info);
return ;
}
while(ptr != q->rear){
printf("%d -> ",ptr->info);
ptr = ptr->next;
}
if(q->front != NULL)
printf("%d\n",ptr->info);
return ;
}

int main(){
LinkQueue queue;
int i;
initQueue(&queue);
deQueue(&queue);
deQueue(&queue);
for(i=0;i<10;i++){
enQueue(&queue,i);
printQueue(&queue);
}
for(i=0;i<12;i++){
if(0 == deQueue(&queue));
printQueue(&queue);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: