链队列

 //链队列
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define OVERFLOW 0
#define OK 1
#define ERROR 0
 
typedef  int Elemt;

//链队列结点
typedef struct QNode{
 int data;
 struct QNode * next;
}QNode,*QueuePtr;

//链对列的头结点和为结点
typedef struct {
QueuePtr front ;
QueuePtr rear;
}LinkQueue;


// 构建一个空的链队列

Elemt  creat_Queue(LinkQueue &Q){
 Q.rear=Q.front=(QueuePtr)malloc(sizeof(QNode)) ;
 if(!Q.rear)  exit(OVERFLOW);
 Q.front->next=NULL;
 printf("creat successful!!!\n");

 return OK;
}

//销毁该链队列
Elemt destory_Queue(LinkQueue &Q){
 while(Q.front){
  Q.rear=Q.front->next;
  free(Q.front);
  Q.front=Q.rear;
 }

 printf("destory successful!!!\n");
 return OK;
}


//判断链对列是否为空,若为空返回OK,否则返回ERROR
Elemt determin_Queue_null(LinkQueue &Q){
 if(Q.front==NULL) return OK;
 else return ERROR;
}

//将该链队列清空
void clear_Queue(LinkQueue &Q){
 destory_Queue(Q);
 creat_Queue(Q); 
}

//判断该链队列的长度,用 e返回
void Queue_lengtu(LinkQueue Q,int &e){
 int n=0;
 QueuePtr p=Q.front;
 while(p!= Q.rear){
  n++;
  p=p->next ;
  
 }
 e=n;
}


//用e返回该链队列的队头
Elemt Gethead(LinkQueue Q,int &e ){
 QueuePtr p;
 p=Q.front;
 if(Q.front == Q.rear) return ERROR;
 p=p->next;
 e=p->data;
 return OK;
}

Elemt in_Queue(LinkQueue &Q,int e){
 QueuePtr p;
 p=(QueuePtr)malloc(sizeof(QNode));
 if(!p) return ERROR;
 p->data = e;
 p->next =NULL;
 Q.rear->next=p;//这是将该结点连接到为部
 Q.rear=p; //这是将该尾部指针指向p(注意这里没有使用Q.rear->next,使用了Q.rear,表示这个结点,指向,而不改变原来的位置的值)
 return OK;
}

//若队列不为空,则删除队头元素
Elemt DEL_Queue_F(LinkQueue &Q){
 QueuePtr p;
 p=Q.front->next;
 if(determin_Queue_null(Q)) return ERROR;
 Q.front->next=p->next;
 if(Q.rear == p) {Q.rear = Q.front; return ERROR;}//注意这里若删除的第一个结点恰好是尾结点的话,是将Q.rear指向Q.front,不能 Q.front=Q.rear(因为此时要删除该尾结点,而不是删除真个链表)
 free(p);
 return OK;

}

//遍历该链队列

Elemt bian_li_Queue(LinkQueue Q){
 QueuePtr p;
 if(determin_Queue_null(Q)) return ERROR;
 p=Q.front->next;
 while(p != NULL){
  printf("%d\n",p->data);
  p=p->next;
 }

 return OK;
 
}

 

int main(){
LinkQueue Q;
int e,n;
creat_Queue(Q);

//clear_Queue(Q);
//Queue_lengtu(Q,e);
for(n=0;n<3;n++){
printf("input your e:\n");
scanf("%d",&e);
in_Queue(Q,e);
}

bian_li_Queue(Q);

//删除链队列头元素
//DEL_Queue_F(Q);

//用e返回该链队列的头元素
//Gethead(Q,e);

//printf("e is : %d\n" ,  e);
destory_Queue(Q);
return OK;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值