/*
*数据结构(队列):队列的链式存储结构
*用单链表实现
*Date:2017/4/16
*/
#include <stdio.h>
#include <stdlib.h>
#define ElemType char
#define InitSize 100
typedef struct LNode{
ElemType data;
struct LNode *next;
}LNode;
typedef struct{
LNode *front,*rear;
int length;
}LinkQueue;
void initQueue(LinkQueue &Q); //初始化队列
bool emptyQueue(LinkQueue Q); //判空操作
void EnQueue(LinkQueue &Q,ElemType e); //入队
void DeQueue(LinkQueue &Q,ElemType &e); //出队
void getHead(LinkQueue Q,ElemType &e); //获取队头元素值
void printQueue(LinkQueue Q); //打印队列
void clearQueue(LinkQueue &Q); //清空队列
void initQueue(LinkQueue &Q){
ElemType e;
Q.front = Q.rear = (LNode *)malloc(sizeof(LNode)); //Q.front 作为头结点
Q.rear->next = NULL;
Q.length = 0;
while(scanf("%c",&e) != EOF && e != '\n'){
if(Q.length < InitSize){
LNode *p = (LNode *)malloc(sizeof(LNode));
p->data = e;
p->next = NULL;
Q.rear->next = p;
Q.rear = p;
Q.length++;
}
}
}
bool emptyQueue(LinkQueue Q){
if(Q.front == Q.rear){
return true;
}else{
return false;
}
}
void EnQueue(LinkQueue &Q,ElemType e){
if(Q.length < InitSize){
LNode *p = (LNode *)malloc(sizeof(LNode));
p->data = e;
p->next = NULL;
Q.rear->next = p;
Q.rear = p;
Q.length++;
}
}
void DeQueue(LinkQueue &Q,ElemType &e){
if(!emptyQueue(Q)){
LNode *p;
e = Q.front->next->data;
p = Q.front->next;
Q.front->next = p->next;
free(p);
Q.length--;
}
}
void getHead(LinkQueue Q,ElemType &e){
if(!emptyQueue(Q))
e = Q.front->next->data;
}
void printQueue(LinkQueue Q){
LNode *p = Q.front->next;
while(p != NULL){
printf("%c",p->data);
p = p->next;
}
printf("\n");
}
void clearQueue(LinkQueue &Q){
LNode * p = Q.front;
while(Q.front != Q.rear){
Q.front = p->next;
free(p);
p = Q.front;
}
free(Q.rear);
printf("队列已经清空\n");
}
int main(){
freopen("in.txt","r",stdin);
LinkQueue Q;
ElemType e;
initQueue(Q);
printQueue(Q);
EnQueue(Q,'A');
printf("EnQueue(&Q,'A'):\n");
printQueue(Q);
DeQueue(Q,e);
printf("DeQueue(&Q,e):%c\n",e);
printQueue(Q);
getHead(Q,e);
printf("getHead(Q,e):%c\n",e);
if(emptyQueue(Q)){
printf("Q is NULL\n");
}else{
printf("Q isn't NULL\n");
}
clearQueue(Q);
if(emptyQueue(Q)){
printf("Q is NULL\n");
}else{
printf("Q isn't NULL\n");
}
return 0;
}
in.txt:
peer