1. 程式人生 > 其它 >考研C語言資料結構-鏈隊(佇列的鏈式儲存實現)

考研C語言資料結構-鏈隊(佇列的鏈式儲存實現)

#include <stdio.h>
#include <stdlib.h>

// 定義結點資料型別
typedef struct LNode {

	int data;
	struct LNode *next;
}LNode;

// 定義鏈隊資料型別
typedef struct {

	LNode *front, *rear;
}LiQueue;

void initLiQueue(LiQueue &Q) {

	Q.front = Q.rear = (LNode *)malloc(sizeof(LNode));
	Q.front->next = NULL;
}

// 判斷佇列空
bool isEmpty(LiQueue Q) {

	if(Q.front == Q.rear)
		return true;

	return false;
}

// 入隊操作
void enQueue(LiQueue &Q, int e) {

	LNode *p = (LNode *)malloc(sizeof(LNode));

	p->data = e;

	p->next = NULL;

	Q.rear->next = p;

	Q.rear = p;
}

// 出隊操作
bool deQueue(LiQueue &Q, int &e) {

	if(isEmpty(Q))
		return false;

	LNode *p = Q.front->next;

	e = p->data;

	Q.front->next = p->next;

	// 如果出隊元素是佇列的最後一個元素,需要修改尾指標
	if(p == Q.rear)
		Q.rear = Q.front;

	free(p);

	return true;
}

int main(void) {

	LiQueue Q;

	initLiQueue(Q);

	enQueue(Q, 1);
	enQueue(Q, 2);
	enQueue(Q, 3);

	int e = -1;
	deQueue(Q, e);
	printf("出隊元素:%d\n", e);
	deQueue(Q, e);
	printf("出隊元素:%d\n", e);
	deQueue(Q, e);
	printf("出隊元素:%d\n", e);

	if(isEmpty(Q))
		printf("佇列已空。\n");

	system("pause");
	return 0;
}