C语言使用链表队列实现初始化,出队列,入队列,取队头,遍历

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;	
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值