数据结构作业一
一队人站成一排,从左到右按1,2,1,2的序号报数,报1的出列,报2的站到最右端,直到所有人出队,用环形队列和链队实现排队序列的输出。
后续持续更新,比较简单只有代码,不解释,有问题可以交流
链队实现 源代码
#include<iostream>
using namespace std;
typedef struct node
{
node* next;
int data;
}mynode;
typedef struct queue
{
node* front;
node* rear;
}myqueue;
void init(myqueue*& q)
{
q = new myqueue;
q->front = q->rear = NULL;
}
bool isempty(myqueue* q)
{
return q->front == NULL;
}
bool enque(myqueue*& q, int e)
{
node* p = new node;
p->data = e;
p->next = NULL;//初始化
if (q->front == NULL)//空队列
{
q->rear = q->front = p;
}
else
{
q->rear->next = p;
q->rear = p;//更新尾节点
}
return true;
}
bool deque(myqueue*& q, int& e)
{
if (isempty(q))//当前链表尾空
{
return false;
}
else if (q->front->next == NULL)//只有一个节点
{
e = q->front->data;
q->front = q->rear = NULL;
return true;
}
node* p = q->front;//保存首节点
e = p->data;
q->front = p->next;//跟新头节点
delete p;
return true;
}
void destroy(myqueue*& q)
{
if (!isempty(q))
{
node* pre = q->front;
node* p = pre->next;
while (p != NULL)
{
delete pre;
pre = p;
p = p->next;
}
delete pre;
}
}
void test(myqueue*& q, int arr[])
{
int e;
int flag = 0;//定义标志,记录出队次序
for (int i = 0; i < 8; i++)
{
enque(q, arr[i]);
}
cout << "链队出队序列为" << endl;
while(!isempty(q))
{
deque(q, e);
flag++;//出队次序+1
if (flag % 2 == 1)
{
cout << e << "\t";
}
else
{
enque(q, e);
}
}
}
int main()
{
queue* q;
int e;
int arr[] = { 1,2,3,4,5,6,7,8 };
init(q);
test(q, arr);
destroy(q);
return 0;
}
环形队列实现 源代码
#include <iostream>
#define MAX 10
using namespace std;
typedef int mytype;
typedef struct queue
{
mytype data[MAX];
int front;
int rear;
}mystruct;
void init(mystruct*& q)
{
q = new mystruct;
q->front = 0;
q->rear = 0;
}
bool enque(mystruct*& q, mytype e)
{
if ((q->front + MAX - q->rear) == 1)//尾指针追上头指针此时队满
{
return false;
}
q->data[q->rear] = e;//原先的队头出没有存放元素
q->rear = (q->rear + 1) % MAX;//再取余
}
bool deque(mystruct*& q, mytype& e)
{
if (q->front == q->rear)
{
return false;
}
e = q->data[q->front];
q->front = (q->front + 1) % MAX;
}
void destroy(mystruct*& q)
{
delete q;
}
bool isempty(mystruct* q)
{
return q->front == q->rear;
}
void test(mystruct*& q, mytype arr[])
{
int flag=0;//定义标志,区分出队的次序是奇数还是偶数
mytype e;
for (int i = 0; i < 8; i++)
{
enque(q, arr[i]);
}
cout << "环形队列出队序列为:" << endl;
while(!isempty(q))
{
deque(q, e);
flag++;//出对次序计数
if (flag % 2 == 1)//只与出队次序有关
cout << e << "\t";
else
enque(q, e);
}
}
int main()
{
mystruct* q;
mytype arr[] = { 1,2,3,4,5,6,7,8 };
init(q);
test(q, arr);
destroy(q);
return 0;
}```