C语言使用链表队列实现初始化,出队列,入队列,取队头,遍历
1.C语言使用链表队列实现初始化,出队列,入队列,取队头,遍历
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef int DataType;
typedef struct Node{
DataType data;
struct Node *next;
}Node;
typedef struct
{
Node *front,*rear;
}LinkQueue;
//链队列的初始化
void InitQueue(LinkQueue *Q){
Node *s=(Node*)malloc(sizeof(Node));
s->next=NULL;
Q->front=Q->rear=s;
}
//入队
int EnQueue(LinkQueue *Q,DataType x) {
Node *s=(Node *)malloc(sizeof(Node));
s->data=x;s->next=NULL;
Q->rear->next=s;Q->rear=s;
}
//出队列
int DeQueue(LinkQueue *Q,DataType *ptr)
{
Node *p;
if(Q->rear==Q->front){
printf("下溢错误,删除失败!");
return 0;
}
p=Q->front->next;*ptr=p->data;
Q->front->next=p->next;
if(p->next==NULL)
Q->rear=Q->front;
free(p);
return 0;
}
//取队头
int GetQueue(LinkQueue *Q,DataType *ptr)
{
Node *p=NULL;
if(Q->rear==Q->front)
{
printf("下溢错误,取队头失败");
return 0;
}
p=Q->front->next;
*ptr=p->data;
return 1;
}
//遍历
void Print(LinkQueue *Q){
Node *p=Q->front->next;
while(p!=NULL)
{
printf("%d\t",p->data);
p=p->next;
}
}
int main(){
DataType x;
LinkQueue Q;
InitQueue(&Q);
printf("入队操作!\n");
EnQueue(&Q,2000);
EnQueue(&Q,8);
EnQueue(&Q,16);
if(GetQueue(&Q,&x)==1)
{
printf("队头元素:%d",x);
}
if(DeQueue(&Q,&x)==1){
printf("出队列:%d\n",x) ;
}
printf("\n队列中的元素为:");
Print(&Q);
return 0;
}