标签:
LinkQueue:
//链式队列 #include<iostream> using namespace std; typedef int elemType; struct QNode { elemType data; QNode *next; }; struct LinkQueue { QNode *front; QNode *rear; }; //初始化 void InitQueue(LinkQueue *q) { q->front = q->rear = new QNode; q->front->next = NULL; } //插入元素e为队列新的队尾元素 void EnQueue(LinkQueue *q, elemType e) { QNode *p = new QNode; p->data = e; p->next = NULL; q->rear->next = p; q->rear = p; } //删除队友元素,并打印其值 void DeQueue(LinkQueue *q) { QNode *p = q->front->next; if(q->front==q->rear) cout<<"队列为空"<<endl; else { elemType x = p->data; cout<<"删除队头元素: "<<x<<endl; q->front->next = p->next; if(q->rear == p) q->rear = q->front; delete p; } } //遍历队列 void TraQueue(LinkQueue *q) { QNode *p = q->front->next; int i = 1; if(q->front==q->rear) cout<<"队列为空"<<endl; else { while(p!=q->rear) { cout << i <<":\t"<<p->data<<endl; p = p->next; i++; } cout << i <<":\t"<<q->rear->data<<endl; } } //清空队列 void ClearQueue(LinkQueue *q) { if(q->front==q->rear) cout<<"出错,队列已经为空"<<endl; else { q->rear->next = q->front; delete(q->front); q->front = q->rear; } } //求队列长度 int LengthQueue(LinkQueue *q) { QNode *p = q->front->next; int length = 0; if(q->front!=q->rear) { while(p) { length++; p = p->next; } } return length; } int main() { LinkQueue q; InitQueue(&q); for(int i=1;i<7;i++) EnQueue(&q,i); int length = LengthQueue(&q); cout <<"队列长度为: "<< length <<endl; TraQueue(&q); cout<<endl; DeQueue(&q); TraQueue(&q); cout<<endl; for(int i=0;i<5;i++) DeQueue(&q); TraQueue(&q); cout<<endl; return 0; }
标签:
原文地址:http://www.cnblogs.com/jx-yangbo/p/4857779.html