기사 디렉토리
머리말
이 기사에서는 주로 데이터 구조에서 체인 큐의 기본 작업을 소개합니다.
1. 체인 대기열 정의
typedef struct QueneNode
{
int data;
struct QueneNode* next;
}Node;
typedef struct LinkQuene
{
Node* front;
Node* rear;
}LinkQuene;
2. 체인 큐의 기본 동작
1. 대기열 초기화
//初始化队列
void Init_Quene(LinkQuene& q)
{
Node *p;
p = new Node;
if (!p)
{
cout << "分配内存失败" << endl;
return;
}
p->next = NULL;
q.front = q.rear = p;
}
2. 대기열이 비어 있는지 확인
//判断队列是否为空
int is_Empty_Quene(LinkQuene q)
{
if (q.front == q.rear)
{
return 1;
}
return 0;
}
3. 팀 운영에 참여
//入队操作
void Push_Quene(LinkQuene& q, int e)
{
Node* p;
p = new Node;
if (!p)
{
cout << "分配内存失败" << endl;
return;
}
p->data = e;
p->next = NULL;
q.rear->next = p;
q.rear = p;
}
4. 대기열 제거 작업
//出队操作
void Pop_Quene(LinkQuene& q, int& e)
{
if (is_Empty_Quene(q))
{
return;
}
Node* p;
p = q.front->next;
if (q.front->next==q.rear)
{
q.rear = q.front;
}
e = p->data;
q.front->next = p->next;
delete p;
}
5. 대기열의 헤드 요소에 액세스합니다.
//访问队列中的队首元素
void Get_Top(LinkQuene q, int& a)
{
if (is_Empty_Quene(q))
return;
a = q.front->next->data;
}
6. 대기열 길이 계산
//求队列长度
int Length_Quene(LinkQuene& q)
{
int length = 0;
Node* p = q.front->next;
while(p != NULL)
{
length++;
p = p->next;
}
return length;
}
모든 소스 코드
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
typedef struct QueneNode
{
int data;
struct QueneNode* next;
}Node;
typedef struct LinkQuene
{
Node* front;
Node* rear;
}LinkQuene;
//初始化队列
void Init_Quene(LinkQuene& q)
{
Node *p;
p = new Node;
if (!p)
{
cout << "分配内存失败" << endl;
return;
}
p->next = NULL;
q.front = q.rear = p;
}
//判断队列是否为空
int is_Empty_Quene(LinkQuene q)
{
if (q.front == q.rear)
{
return 1;
}
return 0;
}
//入队操作
void Push_Quene(LinkQuene& q, int e)
{
Node* p;
p = new Node;
if (!p)
{
cout << "分配内存失败" << endl;
return;
}
p->data = e;
p->next = NULL;
q.rear->next = p;
q.rear = p;
}
//出队操作
void Pop_Quene(LinkQuene& q, int& e)
{
if (is_Empty_Quene(q))
{
return;
}
Node* p;
p = q.front->next;
if (q.front->next==q.rear)
{
q.rear = q.front;
}
e = p->data;
q.front->next = p->next;
delete p;
}
//访问队列中的队首元素
void Get_Top(LinkQuene q, int& a)
{
if (is_Empty_Quene(q))
return;
a = q.front->next->data;
}
//求队列长度
int Length_Quene(LinkQuene& q)
{
int length = 0;
Node* p = q.front->next;
while(p != NULL)
{
length++;
p = p->next;
}
return length;
}
int main()
{
LinkQuene q;
Init_Quene(q);
if (is_Empty_Quene(q))
{
cout << "该队列为空" << endl;
}
cout << "该队列的长度为:" << Length_Quene(q) << endl;
Push_Quene(q, 1);
Push_Quene(q, 2);
Push_Quene(q, 3);
int a = 0;
Get_Top(q, a);
cout << "队首元素为:" << a << endl;
cout << "该队列的长度为:" << Length_Quene(q) << endl;
int e = 0;
Pop_Quene(q, e);
Get_Top(q, a);
cout << "队首元素为:" << a << endl;
Pop_Quene(q, e);
Get_Top(q, a);
cout << "队首元素为:" << a << endl;
Pop_Quene(q, e);
cout << "该队列的长度为:" << Length_Quene(q) << endl;
return 0;
}