1.链队:
插入 删除 打印 取队顶
#include <stdio.h> #include <stdlib.h>typedef struct Qnode{int data;struct Qnode *next; }Qnode,*QuenePtr;typedef struct {QuenePtr front;QuenePtr rear; }LinkQueue; //初始化 void InitQueue(LinkQueue *q){(*q).front=(QuenePtr)malloc(sizeof (Qnode));if(!(*q).front) exit(0);(*q).front->next=NULL;(*q).rear=(*q).front; } //销毁 void DestroyQueue(LinkQueue *q){while((*q).front){(*q).rear=(*q).front->next;free((*q).front);(*q).front=(*q).rear;} } //判空 int IsEmpty(LinkQueue q){if(q.rear==q.front) return 1;else return 0; } //入队 void EnQueue(LinkQueue *q,int e){QuenePtr p=(QuenePtr)malloc(sizeof(Qnode));if(!p)exit(0);p->data=e;p->next=NULL;(*q).rear->next=p;(*q).rear=p;} //出队 void DeQueue(LinkQueue *q,int *e){if((*q).rear==((*q).front)) printf("Empty !");QuenePtr p=(*q).front->next;*e=p->data;(*q).front->next=p->next;if((*q).rear ==p) (*q).rear=(*q).front;free(p); } //打印 void Show(LinkQueue *q){for(Qnode *p=q->front->next ;p!=NULL;p=p->next){printf("%d ",p->data);}printf("\n"); }int main(){LinkQueue q;InitQueue(&q);for(int i=0;i<5;i++){int e; scanf("%d",&e);EnQueue(&q,e);}Show(&q);if(IsEmpty(q)) printf("empty!");else printf("not empty");int e;DeQueue(&q,&e); printf("出队元素是:%d \n",e);Show(&q);int val;scanf("%d",&val);DestroyQueue(&q);return 0; }
2.循环队列
wenti
#include<stdio.h>
#include<stdlib.h>
#define Maxsize 100typedef struct {int *base;int front ;int rear;
}SqQueue;//初始化
void InitQueue (SqQueue *q){q->base=(int *)malloc (Maxsize *sizeof (int));if(!q->base) exit(0);q->front=0;q->rear=0;
}
//入队
void EnterQueue(SqQueue *q,int e){if((q->rear+1)%Maxsize==q->front) printf("Full!\n");q->base[q->rear]=e;q->rear=(q->rear +1)%Maxsize;
}
//取队头元素
void getElem(SqQueue q,int *e){if(q.front!=q.rear){*e=q.base[q.front];}else {printf("Empty! \n");}
}
//求队长
int Getlength(SqQueue q){int e;e=(q.rear-q.front+Maxsize)%Maxsize;return e;
}
//出队
void PopQueue(SqQueue *q,int *e){if(q->front==q->rear) printf("Empty! \n");*e=q->base[q->front];q->front=(q->front+1)%Maxsize;
}
//打印
void Print(SqQueue q){for (int i=q.front;i!=q.rear;){printf("%d ",q.base[i]);i=(i+1)%Maxsize;}printf("\n");
}int main(){SqQueue q;int e;for(int i=0;i<5;i++){scanf("%d",&e);EnterQueue(&q,e);}Print(q);getElem(q,&e);printf("队顶元素是 %d \n",e);int length=Getlength(q);printf("队长是%d \n",length);PopQueue(&q,&e);printf("出队元素是%d \n",e);Print(q);return 0;
}