现在的位置: 首页 > 综合 > 正文

队列

2014年02月21日 ⁄ 综合 ⁄ 共 1894字 ⁄ 字号 评论关闭
//queue.h
	//队列,链表存储

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
	typedef int ElemType;
typedef  struct QNode
{ 
	ElemType data;                     
	struct QNode *next;                 
}QNode; 
typedef struct 
{ 
	QNode *front, *rear;            
}L_Queue;    

/****************************************************************/
void init_Q(L_Queue *Q)
{ 
	QNode *p ;
	p=(QNode *)malloc(sizeof(QNode));
	p->next=NULL;
	Q->front=p; Q->rear=p;
}

/****************************************************************/
void out_Q(L_Queue *Q)//put out all elem sof the queue
{ 
	QNode *p;  
	p=Q->front->next;
	while(p!=NULL) { printf("%-4d",p->data);
	p=p->next;
	}
}

/****************************************************************/
void EnQueue(L_Queue *Q,ElemType e)//put  a data in the queue
{ 
	QNode  *s;
	s=(QNode *)malloc(sizeof(QNode));
	s->data=e; s->next=NULL;
	Q->rear->next=s;  Q->rear=s;
}

/****************************************************************/
void destroyQueue(L_Queue *Q)//destroy a queue
{ 
	while(Q->front)
	{Q->rear=Q->front->next;
	free(Q->front);
	Q->front=Q->rear;
	}
}

/****************************************************************/
ElemType DeQueue(L_Queue *Q)//out a data from the queue
{
	QNode *p;ElemType e;
	//if(Q.front ==Q.rear)printf("Wrong");
	p=Q->front->next;
	e=p->data;
	Q->front->next=p->next;
	if(Q->rear==p)Q->rear=Q->front;
	free(p);
	return e;
}

main

/////////////////////////////////////////////////////////////////////

//Queue.cpp

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include"Queue.h"
#define MAXSIZE 20
typedef int ElemType;

L_Queue *q1;
void main()
{
	int k,a,b;ElemType x,y;
	q1=(L_Queue *)malloc(sizeof(L_Queue));
	init_Q(q1);

	do{
		printf("\n\n\t\t******************************\n");
		printf("\t\t**1、进队列                 **\n");
		printf("\t\t**2、出队列                 **\n");
		printf("\t\t**3、输出队列               **\n");
		printf("\t\t**5、结束                   **\n");
		printf("\t\t******************************\n");
		scanf("%d",&k);
		switch(k)
		{
		case 1:{//ElemType y;
			printf("输入进队列元素:");
			scanf("%d",&y);
			EnQueue(q1,y);
			printf("进队列元素是:%d\n",y);
			break;
			   }
		case 2:{x=DeQueue(q1);
			printf("出队列元素是:%d\n",x);
			break;
			   }
		case 3:{out_Q(q1);
			break;
			   }
		}
	}while(k!=4);
}

抱歉!评论已关闭.