不帶頭結點的鏈式隊列進出隊操作


/*
不帶頭結點的鏈式隊列進出隊操作
*/ 
#include <stdio.h>
#include <stdlib.h>
#define ElementType int
typedef struct QNode *Queue;
typedef struct Node{
	ElementType Data;
	struct Node *Next;
};
typedef struct QNode{
	struct Node *front;
	struct Node *rear;
};
void InintQueue(Queue &PtrQ){//雖然是指針,但是沒賦值之前也不能亂指 
	PtrQ = (Queue)malloc(sizeof(struct QNode));
	PtrQ->front=PtrQ->rear=NULL;
}

bool EnQueue(Queue PtrQ, ElementType X){
	struct Node *RearCell = PtrQ->rear;
	struct Node *Tmp = (struct Node *)malloc(sizeof(struct Node));
	Tmp->Data = X;
	Tmp->Next=NULL;
	if(PtrQ->front==NULL)//隊列為空,進第一個元素 
		PtrQ->rear=PtrQ->front=Tmp;
	else{
		PtrQ->rear->Next = Tmp;
		PtrQ->rear = Tmp;
	}
	return true;
}
ElementType DeleteQ(Queue PtrQ){
	struct Node *FrontCell;
	ElementType FrontElem;
	if(PtrQ->front==NULL){
		printf("隊列為空\n");
		return 1; 
	}
	FrontCell = PtrQ->front;
	if(PtrQ->front==PtrQ->rear)//若隊列中只有一個元素 
		PtrQ->front=PtrQ->rear=NULL;//刪除后置空 
	else
		PtrQ->front = PtrQ->front->Next;
	FrontElem = FrontCell->Data;
	free(FrontCell);
	return FrontElem;
}
Is_EmptyQ(Queue PtrQ){
	return PtrQ->front==NULL;
}

int main(){
	Queue PtrQ;
	InintQueue(PtrQ);
	for(int i = 0;i<10;i++)
		EnQueue(PtrQ,i); 
	while(!Is_EmptyQ(PtrQ))
		printf("%d\n",DeleteQ(PtrQ));
	return 0;
}

  


免責聲明!

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



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