链式队列基本操作

来源:互联网 发布:撞客的科学解释 知乎 编辑:程序博客网 时间:2024/04/30 03:55
/*链式队列:使用链节点管理数据成员(C语言实现版)*//*特点:  动态变长,使用链表作为基本数据结构: 头结点-->对头-->.....-->队尾  不存在伪溢出的问题,长度没有限制,但是插入和删除节点的时间代价较高(动态分配空间)*/#include <stdio.h>#include <stdlib.h>/*定义一个链表节点作为基本数据结构*/typedef struct node {int data ;struct node *next ;}QNode ;/*定义队列*/typedef struct{QNode *front; /*头指针*/QNode *rear;  /*尾指针*/}Queue ;/*1、初始化队列*/int InitQueue(Queue *Q){Q->front = Q->rear = malloc(sizeof( QNode)) ; /*分配空间*/if(!Q->front)return -1 ;Q->front->next = NULL ; /*构造一个空队列*/return 0 ;}/*2、清空队列:由于空间随着元素的插入动态分配,清空时也要释放动态空间,回归到初始化状态*/void ClearQueue(Queue *Q){QNode *p ;QNode *q;/*先让尾指针 = 头指针*/Q->rear = Q->front ;p = Q->front->next ;Q->front->next = NULL ;while(p){q = p ;p = p->next ;free(q) ;}}/*3、销毁队列,即将整个队列销毁,包括头结点 ,完全不存在*/void DestroyQueue(Queue *Q){/*从队列的头指针开始销毁每一个节点*/while(Q->front){Q->rear = Q->front->next ;free(Q->front) ;Q->front = Q->rear ;}}/*4、判断队列是否为空:Q->front->next == NULL*/int QueueEmpty(Queue *Q){/*直接判断Q->front->next == NULL */if(Q->front->next == NULL)return 1 ;return 0 ;}/*5、求队列长度,即元素个数*/int GetLen(Queue *Q){int i = 0 ;QNode *p ;p = Q->front ;while(p != Q->rear){i++ ;p = p->next ;}return i ;}/*6、取出头元素保存到e,不删除对头*/int GetHead(Queue *Q, int *e){/*先判断是否为空*/if(QueueEmpty(Q))return -1 ;*e = Q->front->next->data ;/*注意不是Q->fron->data, Q->fron是队列头,不是头元素*/return 0 ;}/*7、删除队头,保存到e,即出队列操作*/int DeQueue(Queue *Q, int *e){QNode *p ;/*先判断是否为空*/if(QueueEmpty(Q))return -1 ;p = Q->front->next ; /*保存头元素*/*e = p->data ;Q->front->next = p->next ;if(Q->rear == p) /*如果要删除的是最后一个节点,使q->rear指向头结点防止出现悬空的指针 */Q->rear = Q->front ;free(p) ;return 0 ;}/*8、插入队尾新元素e,即入队操作*/int EnQueue(Queue *Q, int e){QNode *p = malloc(sizeof(QNode)) ;/*先分配新节点空间*/if(!p)return -1 ;/*设置新节点为尾节点*/p->data = e ;p->next = NULL ;Q->rear->next = p ;Q->rear = p ;return 0 ;}/*9、遍历队列头元素到位元素打印出来*/void PrintQueue(Queue *Q){QNode *p ;if(QueueEmpty(Q)){printf("QueueEmpty ! \n") ;return ;}p = Q->front->next ; /*存储头元素*/printf("PrintQueue begin ! ######### \n") ;while(p != NULL){printf("%d \n" , p->data) ;p = p->next ;}printf("PrintQueue end   ! ######### \n") ;}int main (void){Queue Q ;int e ;InitQueue(&Q);EnQueue(&Q , 1) ;EnQueue(&Q , 2) ;EnQueue(&Q , 3) ;EnQueue(&Q , 4) ;EnQueue(&Q , 5) ;EnQueue(&Q , 6) ;EnQueue(&Q , 7) ;printf("GetLen = %d \n" , GetLen(&Q)) ;PrintQueue(&Q) ;DeQueue(&Q,&e) ;printf("DeQueue = %d \n" ,e) ;printf("GetLen = %d \n" , GetLen(&Q)) ;PrintQueue(&Q) ;return 0 ;}
0 0
原创粉丝点击