队列:FIFO
栈:FILO
本文采用顺序式存储结构来模拟队列与栈的相关操作
具体代码见下
#include<bits/stdc++.h>
using namespace std;
typedef struct stack
{
int top;
int maxsize;
int* element;
}Stack;
void Create(Stack* S, int msize)
{
S->maxsize = msize;
S->top = -1;
S->element = (int*)malloc(sizeof(int) * msize);
}
void Destory(Stack* S)
{
S->maxsize = -1;
free(S->element);
S->top = -1;
}
void Clear(Stack* S)
{
S->top = -1;
}
int Isfull(Stack* S)
{
return S->top == S->maxsize - 1;
}
int Isempty(Stack* S)
{
return S->top == -1;
}
int Top(Stack* S)
{
if (Isempty(S))return 0;
return S->element[S->top];
}
int Push(Stack* S, int x)
{
if (Isfull(S))
{
printf("empty!");
return 0;
}
S->top++;
S->element[S->top] = x;
return 1;
}
int Pop(Stack* S)
{
if (Isempty(S))
{
return 0;
}
S->top--;
return 1;
}
/**手动分割qwq**/
typedef struct queue
{
int front, tail;
int size;
int* element;
}Queue;
void Create(Queue* S, int msize)
{
S->front = 1;
S->tail = 0;
S->size = msize;
S->element = (int*)malloc(sizeof(int) * msize);
}
void Destory(Queue* S)
{
S->size = -1;
free(S->element);
S->front = 0;
S->tail = 0;
}
void Clear(Queue* S)
{
S->front =0;
S->tail = 0;
}
int Isfull(Queue* S)
{
return (S->tail - S->front) == S->size;
}
int Isempty(Queue* S)
{
return S->front==(S->tail+1);
}
int Front(Queue* S)
{
if (Isempty(S))return 0;
return S->element[S->front];
}
int Push(Queue* S, int x)
{
if (Isfull(S))
{
printf("full!");
exit(0);
return 0;
}
S->tail++;
S->element[S->tail] = x;
return 1;
}
int Pop(Queue* S)
{
if (Isempty(S))
{
return 0;
}
S->front++;
return 1;
}
int main()
{
Stack s;
Stack* p;
p = &s;
Queue q;
Queue* pp;
pp = &q;
Create(p,20);
Create(pp, 20);
int x;
while (cin >> x)
{
if (x == 0)break;
if (x > 0)Push(p, x);
else Push(pp, x);
}
while (Top(p))
{
cout << Top(p) <<" ";
Pop(p);
}
cout << endl;
while (Front(pp))
{
cout << Front(pp) << " ";
Pop(pp);
}
}