队列的链式存储结构(c语言实现)

#include 
#include 

#define T 1
#define F 0
#define MAXSIZE 20

typedef int Status;
typedef int ElemType;

typedef struct QNode		//结点结构
{
	ElemType data;
	struct  QNode* next;
}QNode, *QueuePtr;

typedef struct 				//队列的链表结构 
{
	QueuePtr front, rear;	//队头、队尾指针
}LinkQueue;

Status init(LinkQueue* Q);
Status enterQueue(LinkQueue* Q, ElemType e);
Status deleteQueue(LinkQueue* Q, ElemType* e);

int main()
{
	int i= 0, num = 0;
	LinkQueue Q;
	init(&Q);
	for (; i < 10; i++)
	{
		enterQueue(&Q, i);
	}
	for (; i > 0; i--)
	{
		deleteQueue(&Q, &num);
		printf("%d\n", num);
	}
	return 0;
}

Status init(LinkQueue* Q)
{
	QueuePtr s = (QueuePtr)malloc(sizeof(QNode));
	if (NULL == s)
	{
		return F;
	}
	s->data = 0;
	s->next = NULL;
	Q->front = s;		//!!队头指针一直指向头结点
	Q->rear = s;
	return T;
}

Status enterQueue(LinkQueue* Q, ElemType e)
{
	QueuePtr s = (QueuePtr)malloc(sizeof(QNode));
	if (NULL == s)
	{
		return F;
	}
	s->data = e;
	s->next = NULL;
	Q->rear->next = s;
	Q->rear = s;
	return T;
}

Status deleteQueue(LinkQueue* Q, ElemType* e)
{
	QueuePtr temp = NULL;
	if (Q->front == Q->rear)	//记着判断队列是否为空
	{
		return F;
	}
	temp = Q->front->next;
	*e = temp->data;
	Q->front->next = temp->next;
	if (Q->rear == temp)		//若队头是队尾,则删除后将rear指向头结点
	{
		Q->rear = Q->front;
	}
	free(temp);
	return T;
}

运行结果:

队列的链式存储结构(c语言实现)_第1张图片

方法二:

#include 
#include 

#define T 1
#define F 0

typedef struct Node 
{
	int data;
	struct Node *next;
}Node;

typedef struct 
{
	Node *in;
	Node *out;
	int count;
}queue;

int init(queue *q);
int inQueue(queue *q, int e);
int outQueue(queue *q, int *e);

int main()
{
	int i, e;
	queue q;
	init(&q);
	for (i = 0; i < 3; i++)
	{
		inQueue(&q, i);
		outQueue(&q, &e);
		printf("%d\n", e);
	}

	return 0;
}

int init(queue *q)
{
	Node * newNode = (Node*)malloc(sizeof(Node));
	if (NULL == newNode)
	{
		return F;
	}
	newNode->next = NULL;
	newNode->data = 0;
	q->in = newNode;//指向新加入的结点
	q->out = newNode;//out始终指向头结点,出队列 出out->next
	q->count = 0;
	return T;
}

int inQueue(queue *q, int e)
{
	Node * newNode = (Node*)malloc(sizeof(Node));
	if (NULL == newNode)
	{
		return F;
	}
	newNode->next = NULL;
	newNode->data = e;
	q->in->next = newNode;
	q->in = newNode;
	q->count ++;
	return T;
}

int outQueue(queue *q, int *e)
{
	if (0 == q->count)
	{
		return F;
	}
	Node *temp = q->out->next;//要出的结点
	*e = temp->data;
	q->out->next = temp->next;
	free(temp);
	q->count --;
	if (0 == q->count)//删除的是最后一个
	{
		q->in = q->out;//in 复位
	}
	return T;
}

运行结果:

队列的链式存储结构(c语言实现)_第2张图片

你可能感兴趣的:(数据结构)