/*algo3-4.cpp*/
#include<stdio.h>
#include<malloc.h>
typedef char ElemType;
typedef struct qnode
{
ElemType data;
struct qnode *next;
}QNode;
typedef struct
{
QNode *front;
QNode *rear;
}LiQueue;
void InitQueue(LiQueue * &q)
{
q=(LiQueue *)malloc(sizeof(LiQueue));
q->front=q->rear=NULL;
}
void ClearQueue(LiQueue * &q)
{
QNode *p=q->front,*r;
if(p!=NULL)/*釋放資料結點佔用空間*/
{
r=p->next;
while(r!=NULL)
{
free(p);
p=r;r=p->next;
}
}
free(q);/*釋放資料結點佔用空間*/
}
int QueueLength(LiQueue * &q)
{
int n=0;
QNode *p=q->front;
while(p!=NULL)
{
n++;
p=p->next;
}
return n;
}
int QueueEmpty(LiQueue *q)
{
if(q->rear==NULL)
return 1;
else
return 0;
}
void enQueue(LiQueue * &q,ElemType e)
{
QNode *s;
s=(QNode *)malloc(sizeof(QNode));
s->data=e;
s->next=NULL;
if(q->rear==NULL)/*若鏈隊為空白,則新結點是隊首結點又是隊尾結點*/
q->front=q->rear=s;
else
{
q->rear->next=s;/*將*s結點鏈到隊尾,rear指向它*/
q->rear=s;
}
}
int deQueue(LiQueue * &q,ElemType &e)
{
QNode *t;
if(q->rear==NULL)/*隊列為空白*/
return 0;
if(q->front==q->rear)/*隊列中只有一個結點時*/
{
t=q->front;
q->front=q->rear=NULL;
}
else/*隊列中有多個結點時*/
{
t=q->front;
q->front=q->front->next;
}
e=t->data;
free(t);
return 1;
}
/*exp3-4.cpp*/
#include<stdio.h>
#include<malloc.h>
typedef char ElemType;
typedef struct qnode
{
ElemType data;
struct qnode *next;
}QNode;
typedef struct
{
QNode *front;
QNode *rear;
}LiQueue;
extern void InitQueue(LiQueue * &q);
extern void ClearQueue(LiQueue * &q);
extern int QueueLength(LiQueue * &q);
extern int QueueEmpty(LiQueue *q);
extern void enQueue(LiQueue * &q,ElemType e);
extern int deQueue(LiQueue * &q,ElemType &e);
void main()
{
ElemType e;
LiQueue *q;
printf("(1)初始化鏈隊\n");
InitQueue(q);
printf("(2)依次進鏈隊元素a,b,c\n");
enQueue(q,'a');
enQueue(q,'b');
enQueue(q,'c');
printf("(3)鏈隊為%s\n",(QueueEmpty(q)?"空":"非空"));
if(deQueue(q,e)==0)
printf("隊寬,不能出隊\n");
else
printf("(4)出隊一個元素%c\n",e);
printf("(5)鏈隊q的元素個數:%d\n",QueueLength(q));
printf("(6)依次進鏈隊元素d,e,f\n");
enQueue(q,'d');
enQueue(q,'e');
enQueue(q,'f');
printf("(7)鏈隊q的元素個數:%d\n",QueueLength(q));
printf("(8)出鏈隊序列:");
while(!QueueEmpty(q))
{
deQueue(q,e);
printf("%c",e);
}
printf("\n");
printf("(9)釋放鏈隊\n");
ClearQueue(q);
}