题目要求:
我的代码实现:
(1)顺序栈和顺序队列:
#include<stdio.h>
#include<stdlib.h>
#define ElemType int
#define MaxSize 20
//顺序队列的基本数据类型定义:
typedef struct{
ElemType data[MaxSize];
int rear,front;
}SqQueue;
//顺序栈的基本数据类型定义:
typedef struct{
ElemType data[MaxSize];
int top;
}SqStack;
void InitQueue(SqQueue &Q)
{
Q.front=Q.rear=0;
}
void InitStack(SqStack &S)
{
S.top=0; //栈顶指针指向第一个元素的下一个位置
}
bool EnQueue(SqQueue &Q,ElemType x)
{
if(Q.front==((Q.rear+1)%MaxSize))return false;
Q.data[Q.rear]=x;
Q.rear=(Q.rear+1)%MaxSize;
return true;
}
bool DeQueue(SqQueue &Q,ElemType &x)
{
if(Q.front==Q.rear)return false;
x=Q.data[Q.front];
Q.front=(Q.front+1)%MaxSize;
return true;
}
bool Push(SqStack &S,ElemType x)
{
if(S.top==MaxSize)return false;
S.data[S.top++]=x;
return true;
}
bool Pop(SqStack &S,ElemType &x)
{
if(S.top==0)return false;
x=S.data[--S.top];
return true;
}
//逆置队列元素:
void ReverseQueue(SqQueue &Q,SqStack &S)
{
ElemType x;
while(DeQueue(Q,x))
{
if(!Push(S,x))
{
printf("\n队列元素过多\n");
exit(0);
}
}
while(Pop(S,x))
{
EnQueue(Q,x);
}
}
int main()
{
SqQueue Q; //定义顺序队列Q;
SqStack S; //定义顺序栈S
InitQueue(Q);
InitStack(S);
ElemType x;
printf("\n队列元素开始入队:\n");
scanf("%d",&x);
while(x!=9999)
{
if(!EnQueue(Q,x))
{
printf("\n队列已满,入队结束\n");
break;
}
scanf("%d",&x);
}
//逆置队列元素的算法:
ReverseQueue(Q,S);
printf("\n队列元素开始出队:\n");
while(DeQueue(Q,x))printf("%d ",x);
printf("\n");
}
(2)链栈和链队列:
#include<stdio.h>
#include<stdlib.h>
#define ElemType int
//链栈的基本数据类型定义:
typedef struct LinkNode{
ElemType data;
struct LinkNode* next;
}LinkNode,*LinkStack;
//链队列的基本数据类型定义:
typedef struct Node{
ElemType data;
struct Node* next;
}Node;
typedef struct{
Node *front,*rear;
}LinkQueue;
void InitQueue(LinkQueue &Q)
{
Q.front=(Node*)malloc(sizeof(Node));
Q.front->next=NULL;
Q.rear=Q.front;
}
void InitStack(LinkStack &S)
{
S=(LinkStack)malloc(sizeof(LinkNode));
S->next=NULL;
}
void EnLinkQueue(LinkQueue &Q,ElemType x)
{
Node *p=(Node*)malloc(sizeof(Node));
p->data=x;
p->next=NULL;
Q.rear->next=p;
Q.rear=p;
}
bool DeLinkQueue(LinkQueue &Q,ElemType &x)
{
if(Q.front==Q.rear)return false;
Node* p=Q.front->next;
Q.front->next=p->next;
if(Q.rear==p)Q.rear=Q.front;
x=p->data;
free(p);
return true;
}
void PushLink(LinkStack &S,ElemType x)
{
LinkNode *p=(LinkNode*)malloc(sizeof(LinkNode));
p->data=x;
p->next=S->next;
S->next=p;
}
bool PopLink(LinkStack &S,ElemType &x)
{
if(S->next==NULL)return false;
LinkNode *p=S->next;
x=p->data;
S->next=p->next;
free(p);
return true;
}
//逆置队列元素:
void ReverseQueue(LinkQueue &Q,LinkStack &S)
{
ElemType x;
while(DeLinkQueue(Q,x))
{
PushLink(S,x);
}
while(PopLink(S,x))
{
EnLinkQueue(Q,x);
}
}
int main()
{
LinkQueue Q; //定义链队列Q;
LinkStack S; //定义链栈S
InitQueue(Q);
InitStack(S);
ElemType x;
printf("\n队列元素开始入队:\n");
scanf("%d",&x);
while(x!=9999)
{
EnLinkQueue(Q,x);
scanf("%d",&x);
}
//逆置队列元素的算法:
ReverseQueue(Q,S);
printf("\n队列元素开始出队:\n");
while(DeLinkQueue(Q,x))printf("%d ",x);
printf("\n");
free(S);
free(Q.front);
}