我希望使用堆栈逐字翻译句子。
输入:第一名第二名
预期产量:第三名第一
实际产量:三分之三
我通过使用push outside for循环而不是for循环来获得所需的结果。
代码: -
#include <stdio.h>
#define MAX 50
typedef int bool;
#define true 1
#define false 0
typedef struct
{
int top;
char* s[MAX];
} stack;
bool isFull(stack *ps)
{
if(ps->top == MAX - 1)
return true;
else
return false;
}
void push(stack *ps, char* x)
{
if(!isFull(ps))
ps->s[++(ps->top)] = x;
else
printf("Error: overflow\n");
}
void display(stack *ps)
{
int i;
for(i = ps->top; i > -1; i--)
printf("%s ", ps->s[i]);
}
int main()
{
stack sentence;
stack* ps = &sentence;
sentence.top = -1;
int n, i;
char word[20];
printf("No. of words: ");
scanf("%d", &n);
for(i = 0; i < n; i++)
{
scanf("%s", word);
push(ps, word);
}
display(ps);
printf("\n");
}
答案 0 :(得分:0)
堆栈数据类型定义为 -
typedef struct
{
int top;
char* s[MAX];
} stack;
char * s [MAX] - 它是指针数组。你不是在这里分配内存而只是创建一个指针数组,它可以保存每个元素中的字符地址。 在push函数中,您只是将this指针赋值为word的地址。在最后执行for循环之后,word的值是&#34; third&#34;。现在,您在s [0],s [1],s [2]指向的地址处打印值。这些都是目前指向的。
这里第1点是有道理的,因为我们正在实现将保存数据值的堆栈。