数据机构——链队列

  
    
#include < iostream >
using namespace std;

typedef
struct qnode
{
int data;
struct qnode * next;
}Qnode,
* Queueptr; // 创建链 Qnode是struct qnode的别名,Queueptr是struct qnode *的别名
typedef struct
{
Queueptr front;
// 对头指针
Queueptr rear; // 队尾指针
}LinkQueue; // 创建队列

// 初始化队列
void InitQueue(LinkQueue * Q)
{
Q
-> front = (Queueptr) malloc( sizeof (Qnode)); // 队头和队尾指向头结点
if ( ! Q -> front)
{
cout
<< " no memory avaliable " << endl; // 存储分配失败
}
else
{
Q
-> front -> next = NULL;
Q
-> rear = Q -> front;
}
}

// 入队列函数
void Enqueue(LinkQueue * Q, int value)
{
Queueptr newp
= (Queueptr)malloc( sizeof (Qnode));
if ( ! newp)
cout
<< " no memory avaliable " << endl; // 存储分配失败
newp -> data = value;
newp
-> next = NULL;
Q
-> rear -> next = newp; // p插入原队尾
Q -> rear = newp; // p成为新的队尾
}

// 删除队列头函数
int DeQueue(LinkQueue * Q)
{
int x;
Queueptr p
= (Queueptr)malloc( sizeof (Qnode));
if (Q -> front == Q -> rear)
cout
<< " 队列中无元素 " << endl;

p
= Q -> front -> next; // 指向对头结点
x = Q -> front -> next -> data; // 保存对头结点的数据
Q -> front -> next = p -> next; // 将对头结点从链上摘下
if (Q -> rear == p) // 原队中只有一个结点,删去后队列变空,此时队头指针已为空
Q -> rear = NULL;
free(p);
// 释放被删队头结点
return x; // 返回原队头数据
}

// 打印队列函数
int PrintQueue(LinkQueue * Q)
{
if (Q -> front == Q -> rear)
{
cout
<< " is empty " << endl;
return 0 ;
}
Queueptr p
= (Queueptr)malloc( sizeof (Qnode));
p
= Q -> front -> next;
while (p != NULL)
{
cout
<< p -> data << " " ;
p
= p -> next;
}
return 1 ;
}

// 取队列头元素
int QueueTop(LinkQueue * Q)
{
return Q -> front -> next -> data;
}

// 判断队列是否为空
int QueueEmpty(LinkQueue * Q)
{
return Q -> front == Q -> rear;
}

// 返回队列的元素个数
int QueueLen(LinkQueue * Q)
{
Queueptr p
= (Queueptr)malloc( sizeof (Qnode));
p
= Q -> front -> next;
int count = 0 ;
while (p != NULL)
{
count
++ ;
p
= p -> next;
}
return count;
}

// 销毁队列
void DestroyQueue(LinkQueue * Q)
{
while (Q -> front)

{

Q
-> rear = Q -> front -> next;

delete Q
-> front;

Q
-> front = Q -> rear;

}

}

int main()
{
LinkQueue
* Q = (LinkQueue * )malloc( sizeof (LinkQueue));
// 初始化队列
InitQueue(Q);

// 入队列操作
int value;
cout
<< " Input an integer " << endl;
cin
>> value;
while (value != 0 )
{
Enqueue(Q,value);
cin
>> value;
}
PrintQueue(Q);
// 打印队列
cout << endl;
// 出队列操作
cout << DeQueue(Q) << endl;
PrintQueue(Q);
cout
<< endl;
// 取队列顶元素
cout << " the front elme: " << endl;
cout
<< QueueTop(Q) << endl;
// 判断队列是否为空
if (QueueEmpty(Q) == 1 )
cout
<< " is empty " << endl;
else
cout
<< " is not empty " << endl;
// 返回队列的元素个数
cout << " 队列中还有几个数 " << endl;
cout
<< QueueLen(Q) << endl;
// 显示队列
cout << " 剩余的数是: " << endl;
PrintQueue(Q);
cout
<< endl;
// 销毁队列
DestroyQueue(Q);
cout
<< " 销毁之后: " << endl;
PrintQueue(Q);
cout
<< endl;
return 0 ;
}

 

你可能感兴趣的:(队列)