// 不带头节点的链队列实现--殷人昆教材c语言第2版.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
typedef int elemtype;
typedef struct Node {
elemtype data;
struct Node* next;
}LinkNode;
typedef struct {
LinkNode* front, *rear;
}LinkQueue;
void init(LinkQueue& q)
{
q.front = q.rear = NULL;
}
int enqueue(LinkQueue& q,elemtype x)
{
LinkNode* s = (LinkNode*)malloc(sizeof(LinkNode));
s->data = x; s->next = NULL;
if (q.rear == NULL)
{
q.front = q.rear = s;
}
else
{
q.rear->next = s;
q.rear = s;
}
return 1;
}
int dequeue(LinkQueue& q, elemtype& x)
{
if (q.rear == NULL)return 0;
LinkNode* p = q.front; x = p->data;
q.front = p->next;//队头被修改,释放原对头节点
free(p);
if (q.front == NULL)q.rear = NULL;
//队列只有一个元素,被删除,front==null;;所以避免rear悬空做修改处理,空队列条件q.front = q.rear = NULL;
return 1;
}
int getfront(LinkQueue& q, elemtype& x)
{
if (q.front == NULL)return 0;
x = q.front->data;
return 1;
}
int empty(LinkQueue q)
{
return q.front == NULL;//写的多好
}
int size(LinkQueue& q)
{
int j = 0;
LinkNode* p = q.front;
while (p)
{
j++;//j对应循环条件中p是第几个节点
cout << p->data << " ";
p = p->next;
}
return j;
}
int main()
{
LinkQueue q;//不用申请一个LinkQueue节点,因为初始化时,q.rear=q.front=NULL,已经进行处理,刘畅教材写的不够简练
init(q);
enqueue(q, 1);
enqueue(q, 2);
enqueue(q, 3);
enqueue(q, 4);
int k=size(q);
std::cout << "Hello World!\n";
cout << k<<endl;
elemtype x;
dequeue(q,x);
cout << x << endl;
}
不带头节点链队列的基本操作的实现
最新推荐文章于 2024-11-26 22:35:52 发布
1911

被折叠的 条评论
为什么被折叠?



