c - 逆波兰表示法的中缀

标签 c data-structures stack rpn

我正在编写代码将中缀表达式转换为反向表示法,但我的程序在执行文件时崩溃了

typedef struct stack
 {
   char a[400];
   int top;
 }
 stack;
 stack s;
 void push(char *,int);
 int pop();

 int main()
  {
    char x[400];
    int len,i,y;
    puts("Enter string");
    scanf("%s",x);
    len=strlen(x);
    for(i=0;i<len;i++)
      {
//considering user is entering only the small alphabets 

      if((x[i])>=97&&x[i]<=122)
      printf("%s",x[i]);

      else
//if encountering the operator then pushing it into stack

      if(x[i]=='/'||x[i]=='*'||x[i]=='+'||x[i]=='-')
        {
        push(x,i);
        }

      else if(x[i]=='(')
      continue;
//When encountering the ')' then popping the operator

      else
        {
        y=pop();
        printf("%c",y);
        }
    }

  return 0;
 }

将数组及其大小作为参数传递

void push(char *x,int i)
{
  stack s;
  s.top++;
  s.a[s.top]=x[i];
}

找到“)”时返回弹出的运算符

int pop()
 {
   stack s;
   int temp;
   temp=s.a[s.top];
   s.top--;
   return temp;
 }

最佳答案

在你的代码中

printf("%s",x[i]);

是错误的。你想要的是

printf("%c",x[i]);

按照C11标准,章节7.21.6.1 , %s格式说明符

If no l length modifier is present, the argument shall be a pointer to the initial element of an array of character type. ...

但是这里x[i]类型为char .

此外,从第 9 段来看,

If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

因此,您的代码调用 undefined behaviour .

接下来,对于这两个函数,push()pop() ,您正在定义一个局部变量 stack s ;它在每次调用这些函数时创建,并在执行完成时销毁。您可能想改用 gloabl 变量。删除局部变量,它们是不需要的。

此外,对于这两个函数,您都使用 s.top值作为 s.a 的索引数组,但没有对其进行任何边界检查。在使用 push() 之前,您应该检查堆栈满情况 ( pop() ) 和堆栈空情况 ( s.top ) 的数组索引值值作为索引。 s.top 的递增和递减也应该放在支票下面。

<小时/>

编辑:

对于逻辑部分,解析所有输入后,您应该检查堆栈上是否还有要弹出的元素。您应该打印堆栈包含的内容,直到堆栈变空以获得完整符号。检查我下面的评论以了解伪代码的想法。

<小时/>

注意:按照C标准,int main()应该是int main(void)

关于c - 逆波兰表示法的中缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29229998/

相关文章:

c - 如何使用微 Controller 对 Lattice iCE40 ultra 进行编程

c - 最新的系统日志消息被延迟

java - 在java中创建树数据结构?

python - 如何在现有列表后添加列表但不扩展它?

C#堆栈队列组合

C++ - 模板类堆栈实现中的反向函数

c - 从C中的文件中读取特定字段

c++ - 了解 32 位 C 编译器中的 sizeof(char)

c++ - 没有重复的链表

c - 使用 malloc() 和 sizeof() 函数时出错