本题是队列和栈的简单进出问题,队列是先进先出,栈是先进后出,写的过程中犯了很低级的错误,定义指针变量却不给指针开辟空间,下次不能再犯了。
#include <iostream>
#include <string.h>
#include <malloc.h>
using namespace std;
typedef struct zz
{
int data[10];
int top;
} zz;
typedef struct dd
{
int data[110];
int front;
int rear;
} dd;
void pushz(zz *s, int e)
{
s->top++;
s->data[s->top] = e;
}
int popz(zz *s)
{
if (s->top == -1)
return 0;
s->top--;
return 1;
}
void pushd(dd *s, int e)
{
s->data[s->rear] = e;
s->rear++;
}
int popd(dd *s)
{
if (s->front == s->rear)
return 0;
s->front++;
return 1;
}
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
zz *s;
s = (zz *)malloc(sizeof(zz *));
s->top = -1;
dd *S;
S = (dd *)malloc(sizeof(dd *));
S->front = 0;
S->rear = 0;
cout << '3';
for (int i = 0; i < n; i++)
{
char y[10];
int j;
int m1, m2;
int flag1, flag2;
flag1 = flag2 = 0;
cout << 3;
scanf("%s", y);
cin >> j;
if (strcmp(y, "push") == 0)
{
pushz(s, j);
pushd(S, j);
}
else
{
if (!(m1 = popz(s)))
flag1 = 1;
if (!(m2 = popd(S)))
flag2 = 1;
}
if (flag1)
cout << "error" << endl;
else
{
for (int i = s->top; i >= 0; i--)
cout << s->data[i] << ' ';
cout << endl;
}
if (flag2)
cout << "error" << endl;
else
{
for (int i = S->front; i < S->rear; i++)
cout << S->data[i] << ' ';
cout << endl;
}
}
}
}
这个题我调试了我还是一直卡在给栈和队列的初始化上,刚看了初始化是我开辟空间出了问题,
S = (dd *)malloc(sizeof(dd ));而我把sizeof里面多写个*号,跑起来没问题了,但还是没对
最后调试还是没能成功,明天要继续看下队列的初始化。队列的初始化与我写的是一样的,问题是那个弹出时不需要给j赋值所以j每次pop都要吞掉我一个字符。终于过了补一下过了的代码
#include <iostream>
#include <string.h>
#include <malloc.h>
using namespace std;
typedef struct zz
{
int data[110];
int top;
} zz;
typedef struct dd
{
int data[110];
int front;
int rear;
} dd;
void pushz(zz *s, int e)
{
s->top++;
s->data[s->top] = e;
}
int popz(zz *s)
{
if (s->top == -1)
return 0;
s->top--;
return 1;
}
void pushd(dd *s, int e)
{
s->data[s->rear] = e;
s->rear++;
}
int popd(dd *s)
{
if (s->front == s->rear)
return 0;
s->front++;
return 1;
}
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
zz *s;
s = (zz *)malloc(sizeof(zz ));
s->top = -1;
dd *S;
S = (dd *)malloc(sizeof(dd ));
S->front = 0;
S->rear =0;
int flag1, flag2;
flag1 = flag2 = 0;
for (int i = 0; i < n; i++)
{
char y[10];
int j;
int m1, m2;
scanf("%s", y);
if(strcmp(y,"push")==0)
cin >> j;
if (strcmp(y, "push") == 0)
{
pushz(s, j);
pushd(S, j);
}
else
{
if (!(m1 = popz(s)))
flag1 = 1;
if (!(m2 = popd(S)))
flag2 = 1;
}
}
if (flag2)
cout << "error" << endl;
else
{
for (int i = S->front; i < S->rear; i++)
cout << S->data[i] << ' ';
cout << endl;
}
if (flag1)
cout << "error" << endl;
else
{
for (int i = 0; i <=s->top; i++)
cout << s->data[i] << ' ';
cout << endl;
}
}
}
今天要把队列的链式结构给学了