**
C语言 创建一个简单链式队列代码:将字符串逐一入队,再出队列输出。
**
队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头。
要点
1.队列节点:
typedef char Elementype;
typedef struct Node
{
Elementype Element;
struct Node *next;
}NODE;
typedef struct QNode
{
NODE *front,*rear;
}Queue;
2.初始化队列:
void InitQueue(Queue *&team)//初始化一个队列
{
team=(Queue*)malloc(sizeof(Queue));
team->front=NULL;
team->rear=NULL;
}
3.进队操作:
void InsertQueue(Queue *&team,Elementype e)//入队函数
{
NODE *t=(NODE*)malloc(sizeof(NODE));
t->Element=e;
t->next=NULL;
if(team->rear==NULL)
{
team->front=team->rear=t;
}
else
{
team->rear->next=t;
team->rear=t;
}
}
4.出队操作:
bool DeleteQueue(Queue *&team,Elementype &e)//出队函数
{
NODE *t;
if(team->front==NULL)
return false;
if(team->front==team->rear)
{
e=team->front->Element;
t=team->front;
team->front=team->rear=NULL;
}
else
{
e=team->front->Element;
t=team->front;
team->front=team->front->next;
}
free(t);
return true;
}
**
最终源代码:
**
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef char Elementype;
typedef struct Node
{
Elementype Element;
struct Node *next;
}NODE;
typedef struct QNode
{
NODE *front,*rear;
}Queue;
void InitQueue(Queue *&team)//初始化一个队列
{
team=(Queue*)malloc(sizeof(Queue));
team->front=NULL;
team->rear=NULL;
}
void InsertQueue(Queue *&team,Elementype e)//入队函数
{
NODE *t=(NODE*)malloc(sizeof(NODE));
t->Element=e;
t->next=NULL;
if(team->rear==NULL)
{
team->front=team->rear=t;
}
else
{
team->rear->next=t;
team->rear=t;
}
}
bool DeleteQueue(Queue *&team,Elementype &e)//出队函数
{
NODE *t;
if(team->front==NULL)
return false;
if(team->front==team->rear)
{
e=team->front->Element;
t=team->front;
team->front=team->rear=NULL;
}
else
{
e=team->front->Element;
t=team->front;
team->front=team->front->next;
}
free(t);
return true;
}
int main()
{
Queue *group;
char a[20],c=0;
int i,j;
InitQueue(group);
gets(a);
i=strlen(a);
for(j=0;j<i;j++)
{
InsertQueue(group,a[j]);
}
for(j=0;j<i;j++)
{
DeleteQueue(group,c);
printf("%c ",c);
}
system("pause");
return 0;
}