搜档网
当前位置:搜档网 › 链队列的各种基本操作

链队列的各种基本操作

#include
#include
#include

#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define NULL 0
#define OVERFLOW -2

typedef int Status;
typedef char QElemType;

typedef struct QNode {
// 链队列结点的类型定义
QElemType data;
struct QNode *next;
}QNode,*QueuePtr;

typedef struct {
QueuePtr front;
QueuePtr rear;
}LinkQueue;

Status InitQueue (LinkQueue &Q) {
// 建一个空队列Q
Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
if (!Q.front) exit(OVERFLOW);
Q.front->next=NULL;
return OK;
}

Status EmptyQueue (LinkQueue &Q) {
//判断是否为空
if(Q.front==Q.rear)
return TRUE;
else
return FALSE;
}

Status EnQueue (LinkQueue &Q, QElemType a,b,c ) {
//在链队列Q中插入新的队尾结点a b c
p = (QueuePtr)malloc(sizeof (QNode));
if (!p) exit (OVERFLOW);
p->data=a;
p->next=NULL;
Q.rear->next=p;
Q.rear=p;
return OK;

r=(QueuePtr)malloc(sizeof(QNode));
if (!r) exit (OVERFLOW);
r->data=b;
r->next=NULL;
Q.rear->next=r;
Q.rear=r;
return OK;

m=(QueuePtr)malloc(sizeof(QNode));
if (!m) exit (OVERFLOW);
m->data=e;
m->next=NULL;
Q.rear->next=m;
Q.rear=m;
return OK;
}

Status DeQueue (LinkQueue &Q, QElemType &e) {
//若队列不空,则删除Q的队头元素结点,输出的元素是e
if (Q.front = =Q.rear) return ERROR;
p=Q.front->next;
e=p->data;
Q.front->next=p->next;
if(Q.rear= =p) Q.rear=Q.front;
return OK;
}

Status LengthQueue1 (LinkQueue &Q) {
//输出队列长度
if(Q.front==Q.rear)
return ERROR;
else
p=Q.front->next;
while(p)
{
length1++;
p=p->next;
}
}

Status EnQueue (LinkQueue &Q, QElemType d,e,f ) {
//在链队列Q中插入新的队尾结点d e f
t=(QueuePtr)malloc(sizeof(QNode));
if (!t) exit (OVERFLOW);
t->data=a;
t->next=NULL;
Q.rear->next=t;
Q.rear=t;
return OK;

x=(QueuePtr)malloc(sizeof(QNode));
if (!x) exit (OVERFLOW);
x->data=b;
x->next=NULL;
Q.rear->next=x;
Q.rear=x;
return OK;

y=(QueuePtr)malloc(sizeof(QNode));
if (!y) exit (OVERFLOW);
y->data=e;
y->next=NULL;
Q.rear->next=y;
Q.rear=y;
return OK;
}

Status LengthQueue2 (LinkQueue &Q) {
//输出队列长度
if(Q.front==Q.rear)
return 0;
else
p=Q.front->next;
while(p)
{
length2++;
p=p->next;
}
}

Status DestroyQueue (LinkQueue &Q) {
//释放练队列
while(Q.front)
{
Q.rear=Q.front->next;
delete Q.front;
Q.front=Q.rear;
}
}

int main() {
LinkQueue *Q;
ELemtype e;
ELemtype length;
printf("(1)初始化链队列Q\n");
Q=InitQueue(Q);
printf("(2)

链队列Q为%s\n",(EmptyQueue(Q)?"空":"非空"));");
printf("(3)依次进队元素a,b,c;\n");
EnQueue(Q,'a');
EnQueue(Q,'b');
EnQueue(Q,'c');
printf("(4)出队一个元素,该元素=%c\n,e");
printf("(5)输出链队列的长度=%c,length1");
printf("(6)依次进队元素d,e,f;\n");
EnQueue(Q,'d');
EnQueue(Q,'e');
EnQueue(Q,'f');
printf("(7)输出链队列的长度=%c,length2");
printf("(9)释放链队列Queue\n");
DestroyQueue(Q);
}

相关主题