@【数据结构】(链队列 基本函数)
链队列的基本操作函数定义:进队,出队,获取队头队尾元素
#include<stdio.h>
#include<stdlib.h>
#include <iostream>
#define Maxsize 20
using namespace std;
typedef int Elemtype;
//数据结点
typedef struct node
{ /* 定义队列结构 */
int data; /* 队列元素类型为int */
struct node *next;
}QNode;
//链队结点
typedef struct qptr
{
QNode *front;
QNode *rear;
}LQueue;
void EnQueue(LQueue *q,Elemtype x) /* 进队操作 */
{
QNode *p;
p =(QNode*)malloc(sizeof(QNode));
p->data = x; p->next = NULL;
q->rear->next = p;
q->rear = p;
}
int EmptyQue(LQueue *q)//队列是否为空
{
if (q->front == q->rear) return 0;
else return 1;
}
int DeQueue(LQueue *q, Elemtype *x) /* 出队操作 1:对空 */
{
QNode *p;
if(!EmptyQue(q))
{
cout << "队空" << endl; return 0;
}
else
{
p = q->front->next;
q->front->next = p->next;
*x = p->data; free(p);
if (q->front->next == NULL)
q->rear = q->front; //队中只有一个元素的情况下,出队后修改队尾指针
return 1;
}
}
void OutputQueue(LQueue *q) /* 输出队列中元素 */
{
QNode *p;
p = q->front->next;
if (!EmptyQue(q)) cout << "队空";
while (p)
{
cout << p->data<< " ";
p = p->next;
}
cout << endl;
}
void GetBack(LQueue *q)//获取对尾元素
{
cout <<"队尾元素为:"<< q->rear->data;
cout << endl;
}
void GetHead(LQueue *q)//获取对头元素
{
cout << "队头元素为:" << q->front->next->data;
cout << endl;
}
void main()
{
//初始化一个带头结点的链队
LQueue *q; QNode *p;
q = (LQueue*)malloc(sizeof(LQueue)); //申请头、尾指针结点
p = (QNode*)malloc(sizeof(QNode)); //申请链队头结点
p->next = NULL;
q->front = p; q->rear = p;
EnQueue(q, 2); EnQueue(q, 7); EnQueue(q, 4); EnQueue(q, 9);
cout << "队中元素为:";
OutputQueue(q);
int index, x;
while (1) //永真循环
{
cout << "---------------------------------------------" << endl;
cout << "请选择操作:1:进队 " << endl;
cout << " 2:出队 " << endl;
cout << " 3:获取队头元素 " << endl;
cout << " 4:获取队尾元素" << endl;
cout << " 5:列出队列中的元素" << endl;
cout << " 0:退出 " << endl;
cout << "---------------------------------------------" << endl;
cin >> index;
switch (index)
{
case 1:
{
cout << "请输入x:";
cin >> x; EnQueue(q, x);
cout << x << "进队后:"; OutputQueue(q);
break;
}
case 2:
{
DeQueue(q, &x);
cout << x << "出队后:"; OutputQueue(q);
break;
}
case 3:
{
GetHead(q);
break;
}
case 4:
{
GetBack(q);
break;
}
case 5:
{
cout << "输出队中元素:" << endl;
OutputQueue(q);
break;
}
case 0: {break; exit(0); }
}
}
system("pause");
}
测试示例:
进队:
出队一个元素:
获取队头元素:
输出队中元素: