链队列基本运算(实验题3.4)
虽然都是基本的数据结构,也很简单,但是亲自打下代码还是收获不小。
都是编译过了的。
// //LiQueue.h //链队基本运算 //2013-10-15 22:49 // #pragma once typedef int ElemType; struct QNode { ElemType data; QNode* next; }; struct LiQueue { QNode* front; QNode* rear; }; void InitQueue(LiQueue* &q); void ClearQueue(LiQueue* &q); void enQueue(LiQueue* &q,ElemType e); //进队 int deQueue(LiQueue* &q,ElemType& e); //出队 void DisQueue(LiQueue* q);
#include "LiQueue.h" #include <malloc.h> #include <stdio.h> void InitQueue( LiQueue* &q ) { q = (LiQueue*)malloc(sizeof(LiQueue)); q->front = q->rear = NULL; } void ClearQueue( LiQueue* &q ) { QNode* p = q->front,*t = p->next; while( NULL != t) { free(p); p = t; t = t->next; } } void enQueue( LiQueue* &q,ElemType e ) { QNode* s = (QNode*)malloc(sizeof(LiQueue)); s->data = e; s->next = NULL; if (q->rear == NULL) //空队 { q->rear = q->front = s; } else { q->rear->next = s; q->rear = s; } } int deQueue( LiQueue* &q,ElemType& e ) { if (q->rear == NULL) //空队 { return 0; } QNode* t = q->front; e = q->front->data; if ( q->front == q->rear) { q->front = q->rear = NULL; } else { q->front = q->front->next; } free(t); return 1; } void DisQueue( LiQueue* q ) { if (q->front == NULL) { return; } QNode* p = q->front; while(p != q->rear) { printf("%d,",p->data); p = p->next; } printf("%d,",p->data); printf("\n"); }
#include "LiQueue.h" int main() { LiQueue* q; InitQueue(q); enQueue(q,1); DisQueue(q); enQueue(q,2); DisQueue(q); enQueue(q,3); DisQueue(q); enQueue(q,4); DisQueue(q); enQueue(q,5); DisQueue(q); ElemType data; deQueue(q,data); DisQueue(q); ClearQueue(q); return 0; }