日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C語言實現順序循環隊列實例_C 語言

作者:犀牛超人 ? 更新時間: 2022-04-16 編程語言

一、隊列和循環隊列基本概念

隊列:

和棧相反,隊列是一種先進先出(FIFO)的線性表。只允許在一端插入,在另一端刪除。

允許插入的叫"隊尾"(rear),允許刪除的叫"隊頭"(front)。

入隊操作:L->rear++;?? L->data[L->rear]=x;(需要入隊的元素)

出隊操作:L->front++;? x=L->data[L->front];

求隊長:隊長=(L->rear)-(L->front);

隊空:L->rear==L->front==-1;

隊滿:隊長=max

使用場景:一切具備先來后到的任務場景

循環隊列:

??和隊列類似,只不過隊頭和隊尾相連,解決了隊列的假溢出現象(隊尾指針達到申請空間的最大時,系統會認定空間滿,但是隊頭指針如果不為-1則就是假溢出)。
入隊:L->rear==(L->rear+1)%max;
出隊:L->front==(L->front+1)%max;
隊滿:由圖可知 隊滿和隊空條件重復,所以為了避免這一情況現如今有兩種方法:1.少用一個元素空間,也就是說front指針在定義時指向0的位置,這樣才能使front和rear之間空出一個元素空間。2.這個方法比較容易理解,就是定義一個Num值來記錄元素個數,num==0時則隊空,num==max時則隊滿。
具體操作:(L->rear+1)%max==front; ?num==max;

隊空:L->rear==L->front;
隊長:分兩種情況:1.頭指針在尾指針之后:按普通隊列求法。2.頭指針在尾指針之前:隊長=L->rear+(max-(L->front));

二、代碼實操

?圖示:

?具體代碼:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define ture 1
#define false 0
#define max 5
typedef struct {
	int data[max];
	int front,rear;
}cteam,*team;
static int num=0;  //全局變量 num  
//初始隊列
int Initteam(team &L){
	L=(cteam *)malloc(sizeof(cteam));
	if(L==NULL){
		printf("申請空間失敗!");
		return false;
	}
	L->front=L->rear=-1;
	return true;
}
//入隊
int pushteam(team &L,int x){
	if(num==max){
		printf("隊滿");
		return false;
	}else{
		L->rear=(L->rear+1)%max;  //rear始終在0-10中循環
		L->data[L->rear]=x; 
		num++;
		return true;
	}
} 
//出隊
int popteam(team &L,int &x){
	if(num==0){
		printf("隊空!");
		return false;
	}else{
		L->front=(L->front+1)%max;  //front始終在0-10中循環
		x=L->data[L->front];
		num--;
		printf("\n%d出隊\n",x);
		return x;
	} 
}
//遍歷隊
void printteam(team L){
	int p;
	p=L->front+1;
	if(L->front<L->rear){
		while(p<=L->rear){
		printf("%d ",L->data[p]);
		p++;}
	}else{
		while((p-1)!=L->rear){
			printf("%d ",L->data[p]);
			p=(p+1)%max;
		}
	}
  }
//求隊長 
 int teamlength(team L){
 	int p;
 	if(L->front<L->rear){
 		p=(L->rear)-(L->front);      //當隊列正常時 
	 }else{
	 	p=L->rear+(max-(L->front));  //當隊列開始循環時 
	 }
	printf("\n隊長為:%d",p);
 }
 //取隊頭元素
  int gettop(team L){
  	if(L->front==L->rear){
  		printf("隊空!");
  		return false;
	  }else{
	  	int t=L->data[L->front+1];
	  	return t;
	  }
  } 
  
  
  /*     
  		pushteam:入隊函數	popteam:出隊函數 
  		printteam:遍歷函數	gettop:取隊頭函數 
  		Initteam:初始化函數	teamlength:求隊長函數 
  */
  
  
int main(){
	team s;
	int w;
	Initteam(s);
	//1-3進隊列 
	pushteam(s,1);      
	pushteam(s,2);
	pushteam(s,3);
	printf("------1-3進隊列后----------\n");
	printf("此時隊列為:");
	printteam(s);
   	popteam(s,w);
	popteam(s,w);
	printf("此時隊列為:");
	printteam(s);
	printf("\n------4-6進隊列后----------\n");
	pushteam(s,4);
	pushteam(s,5);
	pushteam(s,6);
	printf("此時隊列為:");
	printteam(s);
	teamlength(s);
	int T=gettop(s);
	printf("\n隊頭元素為:%d",T);
}

實現結果:

總結

原文鏈接:https://blog.csdn.net/m0_61395860/article/details/122847003

欄目分類
最近更新