C語言實現隊列基本操作-初始化,入隊,出隊,打印,刪除


C語言實現隊列基本操作-初始化,入隊,出隊,打印,刪除

C語言:

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

// 隊列的實現
#define OVERFLOW -2 
#define OK 1
#define ERROR 0

typedef int Status;
typedef int QElemType;
 
typedef struct QNode{
	QElemType data;
	struct QNode * next;
}QNode, *QueuePtr;
typedef struct {
	QueuePtr front;            // 隊頭指針 
	QueuePtr rear;             // 隊尾指針 
}LinkQueue;

Status InitQueue(LinkQueue &Q)
{
	// 構造一個空隊列
	Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
	if(!Q.front) exit(OVERFLOW);         // 分配存儲失敗 
	Q.front->next = NULL;
	return OK;
}

Status DestroyQueue(LinkQueue &Q)
{
	// 銷毀隊列 Q
	while(Q.front){
		Q.rear = Q.front->next;
		free(Q.front);
		Q.front = Q.rear;
	} 
	return OK;
}

Status EnQueue(LinkQueue &Q, QElemType e)
{
	// 插入元素 e 為 Q 的新的隊列元素 
	QueuePtr p = (QueuePtr)malloc(sizeof(QNode));
	if(!p) exit(OVERFLOW);          // 存儲分配失敗
	p->data = e;
	p->next = NULL;                // 隊尾 next == NULL,有 data 
	Q.rear->next = p;
	Q.rear = p;                    // 更新隊尾 
	return OK; 
}

Status DeQueue(LinkQueue &Q, QElemType &e)
{
	// 若對頭不空,則刪除對頭元素,用 e 返回其值,並返回 OK,否則返回 ERROR
	if(Q.front == Q.rear) return ERROR;
	QueuePtr p = Q.front->next;         // Q.front 沒有 data, next != NULL(除非空隊列) 
	e = p->data;
	Q.front->next = p->next;            // 更新隊頭 
	if(Q.rear == p) Q.rear = Q.front;   // 隊列為空了 
	free(p);
	return OK;
}

Status PrintQueue(LinkQueue Q)
{
	// 打印隊列 Q 全部元素 
	QueuePtr p = Q.front;
	while(p->next){
		printf("%d ", p->next->data);
		p = p->next;
	}
	printf("\n"); 
}
int main()
{
	LinkQueue q;
	InitQueue(q);       // 初始化隊列
	
	QElemType e1 = 666, e2 = 888;    // 向隊列添加元素 
	EnQueue(q, e1);
	EnQueue(q, e2);
	printf("隊列元素: "); 
	PrintQueue(q);        // 打印隊列 
	
	QElemType e3;
	DeQueue(q, e3);
	printf("刪除元素為: %d \n", e3);
	printf("隊列元素: "); 
	PrintQueue(q);        // 打印隊列 
	
	DestroyQueue(q);      // 刪除隊列 
	
	return 0;
}
/* Code Running Results 隊列元素: 666 888 刪除元素為: 666 隊列元素: 888 */

棧和單鏈線性表基本操作實現:

單鏈線性表


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM