#include <iostream>
using namespace std;
typedef int QElemType;
//链队结构定义
typedef struct QNode {
QElemType data;
struct QNode *next;
}QNode, *QueuePtr;
typedef struct
{
QueuePtr front; //队头指针
QueuePtr rear; //队尾指针
}LinkQueue;
//链队初始化
int InitQueue(LinkQueue &Q)
{
Q.front = Q.rear = new QNode; //给队头指针和队尾指针开辟内存
if (!Q.front) return -2;
Q.front = NULL; //将队头指针指向空
return 0;
}
//链队销毁
int DestroyQueue(LinkQueue &Q)
{
QueuePtr p = (QueuePtr)malloc(sizeof(QNode)); //此处可以写为QNode *p
while (Q.front)
{
p = Q.front->next;
delete Q.front;
Q.front = p;
}
cout << "销毁成功" << endl;
return 0;
}
//链队入队
bool EnQueue(LinkQueue &Q, QElemType e)
{
QNode *p = new QNode;
if (!p)
return false;
p->data = e;
p->next = NULL;
Q.rear->next = p;
Q.rear = p;
return true;
}
//链队出队
int DeQueue(LinkQueue &Q, QElemType &e)
{
QNode *p = new QNode;
if (Q.front == Q.rear)return -1;
p = Q.front->next; //将要出队的元素位置存放在p中
e = p->data; //将要出队的元素值存放在e中
Q.front->next = p->next; //头指针后移
if (p = Q.rear) //如果要出队的是队尾元素,应该将队头指针赋值给队尾指针
Q.rear = Q.front;
delete p;
return 0;
}
//遍历
int TraverseQueue(LinkQueue Q) {
if (Q.front == Q.rear) return -1;
auto p = Q.front->next;
cout << "遍历链队: ";
while (p) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
return 0;
}
int main()
{
LinkQueue Q;
InitQueue(Q);
EnQueue(Q, 10);
TraverseQueue(Q);
system("pause");
}
青岛大学王卓老师数据结构——C++实现链队
最新推荐文章于 2024-06-27 16:24:34 发布