zoukankan      html  css  js  c++  java
  • 数据结构之链栈写的括号匹配


    #include<iostream>
    #include<stdio.h>
    #include<malloc.h>
    #include<string.h>
    #include<stdlib.h>
    #define maxsize 100
    using namespace std;
    typedef struct node
    {
    char data;
    struct node *next;
    }lnode ,*linkstack;

    void init(linkstack *top)
    {
    if( ( (*top)=(linkstack)malloc(sizeof(lnode)) )==NULL )//(给*top分配一个存储空间让top指向这个空间)
    exit(-1);
    (*top)->next=NULL;

    }
    int empty(linkstack top)
    {
    if(top->next==NULL)
    return 1;
    else
    return 0;
    }
    int get(linkstack top,char *e)
    {
    lnode *p;
    p=top->next;
    if(!p)
    {
    cout<<"栈已空!";
    return 0;
    }
    else
    {
    *e=p->data;
    return 1;
    }
    }


    int push(linkstack top,char e)
    {
    lnode *p;
    if( (p=(linkstack)malloc(sizeof(lnode)))==NULL )//(给*top分配一个存储空间让top指向这个空间)
    {
    printf("分配内存失败");
    exit(-1);
    return 0;
    }

    p->data=e;
    p->next=top->next;
    top->next=p;
    return 1;

    }
    int pop(linkstack top,char *e)
    {
    linkstack p=top->next;
    if(p==NULL)
    {
    cout<<"栈已空!";
    return 0;
    }

    top->next=p->next;
    *e=p->data;
    free(p);
    return 1;
    }


    int length(linkstack top)
    {
    int i=0;
    lnode *p=top;
    while(p->next!=NULL)
    {
    p=p->next;
    i++;
    }
    return i;
    }

    void clear(linkstack top)
    {
    lnode *p,*q;
    p=top;
    while(!p)
    {
    q=p;
    p=p->next;
    free(q);
    }
    }

    int match(char e,char ch)
    {
    if(e=='(' && ch==')')
    return 1;
    else if(e=='['&&ch==']')
    return 1;
    else if(e=='{'&&ch=='}')
    return 1;
    else
    return 0;
    }
    int main()
    {
    linkstack s;
    lnode *p;
    int i,len;
    char e;
    string ch="{4*(8-3)-[(7*2)*5-9]}*3-9*(5-2)";
    len=ch.length();
    init(&s);
    cout<<"将带括号的表达式依次入栈!"<<endl;
    cout<<"{4*(8-3)-[(7*2)*5-9]}*3-9*(5-2)"<<endl;
    for(i=0;i<len;i++)
    {
    switch(ch[i])
    {
    case '(':
    case '[':
    case '{':
    push(s,ch[i]);
    break;
    case ')':
    case ']':
    case '}':
    if(empty(s))
    {
    cout<<"缺少左括号"<<endl;
    return 0;
    }
    else
    {
    get(s,&e);
    if(match(e,ch[i]))
    {
    pop(s,&e);
    }

    else
    {
    cout<<"左右括号不匹配";
    return 0;
    }
    }

    }
    }
    if(empty(s))
    printf("阔号匹配!");
    else
    cout<<"缺少右括号!";

    }

  • 相关阅读:
    一款全屏图片滑动js 插件 超快捷
    19个非常有用的 jQuery 图片滑动插件和教程
    sqlite 下载的 ZIP 包的区别
    get utc+8 当时时间
    http://www.dayandeng.com/ 诈骗网站
    This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms
    c# string 数组转 list
    sql在添加新列时同时指定default约束名称
    windows证书地址
    Value Dispose() cannot be called while doing CreateHandle().
  • 原文地址:https://www.cnblogs.com/mykonons/p/6600595.html
Copyright © 2011-2022 走看看