链队列

用链表表示的队列简称为链队列。为了操作方便,通常采用带头结点
的链表结构,并设置一个队头指针和一个队尾指针。队头指针始终指
向头结点, 队尾指针指向当前准后一个元素。空的链队列的队头指针
和队尾指针均指向头结点。

队列的链式存储结构描述
typedef struct QNode
{//链队列元素结点类型
 QElemType data;
 struct QNode *next;
}QNode, *QueuePtr;

typedef struct LinkQueue
{//链队列类型
 QueuePtr *front;
 QueuePtr *rear;
}LinkQueue;

初始化链队列
int InitQueue(LinkQueue &Q)
{
 Q.front = (QueuePtr)malloc(sizeof(QNode));
 if (Q.front == NULL)
  exit(OVERFLOW);
 Q.rear = Q.front;
 Q.front->next = NULL;
 return OK;
}

向链队列中插入元素
int EnQueue(LinkQueue &Q, QElemType e)
{
 QueuePtr s;
 s = (QueuePtr)malloc(sizeof(Qnode));
 if (s == NULL)
  exit(OVERFLOW);
 s->data = e;
 s->next = NULL;
 Q.rear->next = s;
 Q.rear = s;
 return OK;
}

从链队列中删除元素
int DeQueue(LinkQueue &Q, QElemType &e)
{
 QueuePtr p;
 if (Q.front == Q.rear)
  return ERROR;
 p = Q.front->next;
 Q.front = p->next;
 if (Q.rear == p)
  Q.rear = Q.front; /*若队列中仅有一个元素,
       则p出队后成为空栈*/
 e = p->data;
 free(p);
 return OK;
}

 

//链队列的简单操作
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

typedef struct QNode
{
	int data;
	struct QNode *next;
}QNode, *QueuePtr;

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

int InitQueue(LinkQueue &Q);
int EnQueue(LinkQueue &Q, int e);
int DeQueue(LinkQueue &Q, int &e);

int main(void)
{
	int i, e;
	LinkQueue Q;
	InitQueue(Q);
	for (i=0; i<10; i++)
		EnQueue(Q, i);
	for(i=1; i<=7; i++)
	{
		DeQueue(Q, e);
		printf("%d ", e);
	}
	printf("\n");
	return 0;
}

int InitQueue(LinkQueue &Q)
{
	Q.front = (QueuePtr)malloc(sizeof(QNode));
	if (Q.rear == NULL)
		exit(1);
	Q.rear = Q.front;
	Q.front->next = NULL;
	return 0;
}

int EnQueue(LinkQueue &Q, int e)
{
	QNode *s = (QueuePtr)malloc(sizeof(QNode));
	if (s == NULL)
		exit(1);
	s->data = e;
	s->next = NULL;
	Q.rear->next = s;
	Q.rear = s;
	return 0;
}

int DeQueue(LinkQueue &Q, int &e)
{
	QueuePtr p;
	if (Q.front == Q.rear)
		return 1;
	p = Q.front->next;
	Q.front->next = p->next;
	if (p == Q.rear)
		Q.rear = Q.front;
	e = p->data;
	free(p);
	return 0;
}


 

posted on 2012-11-30 21:36  zm001  阅读(221)  评论(0)    收藏  举报