标题:自己写了一个链栈操作,来实现括号匹配算法,但是程序运行不下去!求大神指 ...
取消只看楼主
jj369258
Rank: 4
等 级:业余侠客
帖 子:116
专家分:226
注 册:2010-12-2
结帖率:69.57%
已结贴  问题点数:10 回复次数:0 
自己写了一个链栈操作,来实现括号匹配算法,但是程序运行不下去!求大神指教!
#include<iostream>
#include<string.h>
#include<ctype.h>

using namespace std;
typedef struct snode
{
    char elem;
    struct snode *next;   
}Link,*Linkstack;

//Linkstack top;

int init_stack(Linkstack top)
{
   if(top->next==NULL)
   return 1;
   else
   return 0;
}

int empty(Linkstack top)//1空返回1,非空返回0
{
    if(top->next==NULL)
    return 1;
    else
    return 0;
}
void push_stack(Linkstack top,char a)//压栈
{
     Linkstack s;
     s=(Linkstack )malloc(sizeof(Link));
      s->elem=a;
     s->next=top->next;
     top->next=s;      
}
int pop_stack(Linkstack top,char a)//出栈
{
    if(empty(top))
    {
        cout<<"栈空!"<<endl;
        return 0;        
    }
    Linkstack s;
    s=(Linkstack )malloc(sizeof(Link));
    s=top->next;
    a=s->elem;
    top->next=s->next;
    free(s);
    return 1;
}
char getop(Linkstack top)//取栈顶元素,返回给a
{
    char a;
    if(empty(top))
    cout<<"栈空!"<<endl;
    a=top->next->elem;
    return a;
}
int main()
{
    Linkstack top;
    int i,length;
    char a,ch,str[100];
    cout<<"请输入要检测的括号对!"<<endl;
    cin>>str;
    length=strlen(str);
  for(i=0;i<length;i++)
  {
   if(str[i]=='('||str[i]=='['||str[i]=='{') /*如果是({【则入栈*/
          push_stack(top,str[i]);
   else
      {
          if(!empty(top))
          {
        ch=getop(top);
        if(ch=='('&&str[i]==')'||ch=='['&&str[i]==']'||ch=='['&&str[i]==']')
            pop_stack(top,a);
           else
           {
                cout<<"括号不匹配!"<<endl;
                return 0;
        }
         }
          else
              {
              cout<<"括号不匹配!"<<endl;
              return 0;
              }
         }                        
  }
    if(i==length&&empty(top))
     cout<<"括号匹配!"<<endl;
     else
     cout<<"括号不匹配!"<<endl;
     return 0;
}

搜索更多相关主题的帖子: top return include 
2012-08-14 21:47



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-379506-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.932948 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved