#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>
#define Size 6
typedef struct SqNode//队列结点
{
int data;
struct SqNode* next;
}LinkNode;
typedef struct SqQueue//队列
{
LinkNode* front, * rear; //头指针和尾指针
}LinkQueue;
typedef struct LinkStack//栈
{
int data;
struct LinkStack* next;
}LinkStack;
void InitQueue(LinkQueue* Q)//假设用带头结点的链表来表示队列
{
Q->front = Q->rear = (LinkNode*)malloc(sizeof(LinkNode));
if (Q->front == NULL)//分配失败
return;
Q->rear->next = NULL;
return;
}
void InitStack(LinkStack** S)//用不带头结点的链表来表示栈,&S表示当前是指向链表指针的指针,所以要用形参要用二级指针
{
*S = NULL;
return;
}
bool EnQueue(LinkQueue* Q, int x)//入队
{
//无需判断满队
LinkNode* s = (LinkNode*)malloc(sizeof(LinkNode));
if (s == NULL)//分配失败
return false;
s->data = x;
s->next = NULL;
Q->rear->next = s;
Q->rear = s;
return true;
}
bool Push(LinkStack** S, int x)//进栈
{
//无需判断是否满栈
//第一次入栈
if ((*S) == NULL)
{
LinkStack* p = (LinkStack*)malloc(sizeof(LinkStack));
if (p == NULL)//分配失败
return false;
p->data = x;
p->next = NULL;
(*S) = p;
}
//后续入栈
else
{
LinkStack* q = (LinkStack*)malloc(sizeof(LinkStack));
if (q == NULL)//分配失败
return false;
q->data = x;
q->next = (*S);
(*S) = q;
}
return true;
}
int* DeQueue(LinkQueue* Q, int* x)//出队
{
if (Q->front == Q->rear)//空队
return NULL;
LinkNode* p = Q->front->next;
if (p == Q->rear)//恰好有一个元素
{
*x = p->data;
Q->front->next = NULL;
free(p);
Q->rear = Q->front;
return x;
}
*x = p->data;
Q->front->next = p->next;
free(p);
return x;
}
bool PrintList(LinkQueue Q)//打印队列
{
LinkNode* p = Q.front->next;
while (p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
return true;
}
bool PrintStack(LinkStack* S)//打印栈
{
LinkStack* p = S;
if (p == NULL)//空栈
return false;
while (p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
return true;
}
int main()
{
int arr[Size] = { 1,2,3,4,5,6 };//假设要输入1,2,3,4,5,6
LinkQueue Q;//定义一个队列
LinkStack* S;//定义一个栈
InitQueue(&Q);//初始化队列
InitStack(&S);//初始化栈
int i;
for(i = 0;i < Size;i++)
EnQueue(&Q,arr[i]);//入队
int* j;
for (i = 0; i < Size; i++)
{
j = DeQueue(&Q, &arr[i]);//出队
Push(&S, *j);//进栈
}
//PrintList(Q);//队列打印测试
PrintStack(S);//栈打印测试
return 0;
}