用链式队列的方式实现输入12345,输出12345操作
1.队列的定义
typedef struct LinkNode{
ElemType data;
struct LinkNode* next;
}LinkNode;
typedef struct {
LinkNode* front, * rear;
}LinkQueue;
2.队列的初始化
void InitQueue(LinkQueue& Q) {
Q.front = Q.rear = (LinkNode*)malloc(sizeof(LinkNode));
Q.front->next = NULL;
}
3.判空操作
bool IsEmpty(LinkQueue Q) {
if (Q.front == Q.rear)
return true;
else
return false;
}
4.入队操作
bool EnQueue(LinkQueue& Q,ElemType x) {
LinkNode* s = (LinkNode*)malloc(sizeof(LinkNode));
s->data = x;
s->next = NULL;
Q.rear->next = s;
Q.rear = s;
return true;
}
5.出队操作
bool DeQueue(LinkQueue& Q, ElemType& x) {
if (Q.front == Q.rear)
return false;
LinkNode* p = Q.front->next;
x = p->data;
Q.front->next = p->next;
if (p->next == Q.front)
Q.rear = Q.front;
free(p);
return true;
}
6.打印出栈元素
void printQueue(LinkQueue Q) {
LinkNode* p = Q.front->next;
while (p!= NULL) {
printf("\t元素%d出栈成功!\n", p->data);
p = p->next;
}
printf("\n");
}
7.源代码
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#define MaxSize 5
typedef int ElemType;
//队列的定义
typedef struct LinkNode{
ElemType data;
struct LinkNode* next;
}LinkNode;
typedef struct {
LinkNode* front, * rear;
}LinkQueue;
//队列的初始化
void InitQueue(LinkQueue& Q) {
Q.front = Q.rear = (LinkNode*)malloc(sizeof(LinkNode));
Q.front->next = NULL;
}
//判空操作
bool IsEmpty(LinkQueue Q) {
if (Q.front == Q.rear)
return true;
else
return false;
}
//入队操作
bool EnQueue(LinkQueue& Q,ElemType x) {
LinkNode* s = (LinkNode*)malloc(sizeof(LinkNode));
s->data = x;
s->next = NULL;
Q.rear->next = s;
Q.rear = s;
return true;
}
//出队操作
bool DeQueue(LinkQueue& Q, ElemType& x) {
if (Q.front == Q.rear)
return false;
LinkNode* p = Q.front->next;
x = p->data;
Q.front->next = p->next;
if (p->next == Q.front)
Q.rear = Q.front;
free(p);
return true;
}
void printQueue(LinkQueue Q) {
LinkNode* p = Q.front->next;
while (p!= NULL) {
printf("\t元素%d出栈成功!\n", p->data);
p = p->next;
}
printf("\n");
}
int main() {
LinkQueue Q;
ElemType x;
int i = 0;
bool ret;
printf("1.初始化队列\n");
InitQueue(Q);
printf("2.栈为:%s\n", (IsEmpty) ? "空" : "非空");
printf("3.请依次入队:\n");
while (i<MaxSize) {
scanf("%d", &x);
EnQueue(Q, x);
printf("\t元素%d入栈成功!\n", x);
i++;
}
printf("4.依次出队操作:\n");
printQueue(Q);
return 0;
}
8.结果展示
输入:1 2 3 4 5
输出:12345