/*
* File name : LinkQueue.cpp
* Function : 链表实现队列 C++实现
* Created on : 2016年4月26日
* Author : beijiwei@qq.com
* Copyright : 欢迎大家和我一起交流学习,转载请保持源文件的完整性。
任何单位和个人不经本人允许不得用于商业用途
*/
#include <cstdio>
#include <iostream>
using namespace std;
typedef int Elem_t;
typedef struct node {
Elem_t data;
struct node * next;
}Node,*pNode;
typedef struct {
pNode head;
pNode tail;
}LinkQueue;
void queue_init(LinkQueue & Q);
void queue_clear(LinkQueue & Q);
bool queue_is_empty(LinkQueue & Q);
void queue_in(LinkQueue & Q, Elem_t elem);
bool queue_out(LinkQueue & Q, Elem_t &elem);
int queue_get_length(LinkQueue & Q);
bool queue_get_head(LinkQueue & Q, Elem_t &elem);
int main(int argc, char** argv)
{
LinkQueue Lq;
Elem_t elem;
queue_init(Lq);
cout << "queue is empty ? " << queue_is_empty(Lq) << endl;
for (int i = 0; i <=5; i++) {
queue_in(Lq, i + 10);
}
cout << "The length of queue is " << queue_get_length(Lq) << endl;
queue_get_head(Lq, elem);
cout << "The head of queue is " << elem << endl;
for (int i = 0; i <= 5; i++) {
queue_out(Lq, elem);
if (i == 3) {
cout << "queue is empty ? " << queue_is_empty(Lq) << endl;
cout << "The length of queue is " << queue_get_length(Lq) << endl;
queue_get_head(Lq, elem);
cout << "The head of queue is " << elem << endl;
}
}
cout << "The length of queue is " << queue_get_length(Lq) << endl;
queue_get_head(Lq, elem);
cout << "The head of queue is " << elem << endl;
return 0;
}
void queue_init(LinkQueue & Q)
{
Q.head = new Node;
Q.tail = Q.head;
Q.head->next = NULL;
Q.head->data = 0;
}
void queue_clear(LinkQueue & Q)
{
pNode p = Q.head;
pNode ptmp = p;
while (p != NULL) {
p = ptmp->next;
delete ptmp;
ptmp = p;
}
}
bool queue_get_head(LinkQueue & Q, Elem_t &elem)
{
if (Q.head == Q.tail) {
cout << "queue is empty can not get" << endl;
return false;
}
elem = Q.head->next->data;
return true;
}
bool queue_is_empty(LinkQueue & Q)
{
return (Q.head == Q.tail) ? true : false;
}
void queue_in(LinkQueue & Q, Elem_t elem)
{
pNode ptmp = new Node;
ptmp->data = elem;
ptmp->next = Q.tail->next;
Q.tail->next = ptmp;
Q.tail = ptmp;
Q.head->data++;
}
bool queue_out(LinkQueue & Q, Elem_t &elem)
{
if (Q.head == Q.tail) {
cout << "queue is empty can not out" << endl;
return false;
}
pNode ptmp = Q.head->next;
elem = ptmp->data;
Q.head->next = Q.head->next->next;
Q.head->data--;
if (Q.head->data == 0)
Q.tail = Q.head;
delete ptmp;
return true;
}
int queue_get_length(LinkQueue & Q)
{
return Q.head->data;
}
链表实现队列 C++实现
最新推荐文章于 2024-04-28 18:45:04 发布