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

c语言链队列的构建

2017-02-13 16:22 148 查看
改代码实现的是输入一串字符然后再屏幕上输出,只是为了验证队列。

c文件

#include <stdio.h>

#include<malloc.h>

#include <string.h>

typedef struct User_type

{
char data;
struct
User_type *next;

} User_type;

#include "Array.h"

/*

//初始化队列 

void initArray(Array **head);

//销毁队列

void destroyArray(Array **head);

//入队列

void push(Array *head,User_type *data);

//出队列 

void pop(Array *head,User_type *data);

*/

int main()

{
Array *head=NULL;
User_type Data;
char a;
initArray(&head);
scanf("%c",&a);

while(a!='0')
{
    Data.data=a;
push(head,&Data);
scanf("%c",&a);
 
}
while(head->front->next!=NULL)
{
pop(head,&Data);
printf("%3c",Data.data);
}
destroyArray(&head);

}

h文件

#ifndef _ARRAY_

#define _ARRAY_

#include <malloc.h>

#include <stdio.h>

typedef struct Array

{
User_type *front;
User_type *end;

}Array;

//初始化队列 

void initArray(Array **head);

//销毁队列

void destroyArray(Array **head);

//入队列

void push(Array *head,User_type *data);

//出队列 

void pop(Array *head,User_type *data);

void pop(Array *head,User_type *data)

{
User_type *p=NULL,*q=NULL;
p=head->front->next;
if(head->end->next==NULL||p==NULL)
{
printf("非法操作!");
}
else
{
data->data=head->front->next->data;
q=p;

head->front->next=p->next;
free(q);
}

}

void push(Array *head,User_type *data)

{
User_type *p=NULL,*q=NULL;
q=head->front->next;
p=(User_type *)(malloc(sizeof(User_type)));
if(q==NULL)
{
head->front->next=p;
head->end->next=p;
}
else
{
head->end->next->next=p;
head->end->next=p;
}
p->data=data->data;
p->next=NULL;

}

void destroyArray(Array **head)

{
User_type *p=NULL,*q=NULL;
q=(*head)->front->next;
p=q;
while(p!=NULL)
{
p=q->next;
free(q);
q=p;
}
free((*head)->front);
free((*head)->end);
free(*head);

}

void initArray(Array **head)

{
if(*head)
{
printf("非法操作!");
}
else
{
(*head)=(Array *)(malloc(sizeof(Array)));
if(*head)
{
(*head)->front=(User_type *)(malloc(sizeof(User_type)));
(*head)->end=(User_type *)(malloc(sizeof(User_type)));
(*head)->front->next=NULL;
(*head)->end->next=NULL;
}
else
{
printf("空间不足!");
}
}

}

#endif
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: