[数据结构-栈]栈的基本操作&括号匹配

来源:互联网 发布:windows启动过程 编辑:程序博客网 时间:2024/05/29 06:31

堆栈的三种实现方式

http://www.cnblogs.com/baochuan/archive/2013/04/11/3010437.html

用静态数据实现

#include<stdio.h>#define MAX_SIZE 100int top = -1;int stack[MAX_SIZE];void init(){    top = -1;}int is_empty(){    return top == -1;}int is_full(){    return top == MAX_SIZE - 1;}void pop(){    if(!is_empty())     {        top--;    }   }void push(int value){    if(!is_full()) stack[++top] = value;}void get_top(){    if(is_empty()) printf("E\n");    else printf("%d\n", stack[top]);}int main(){    int n;    while(1)    {        if(scanf("%d", &n) == 1);        if(n == 0) break;        init();        int i;        for(i = 0; i < n; i ++)        {            char opt;            if(scanf(" %c", &opt));            switch(opt)            {                case 'P':                    {                        int value;                        if(scanf("%d", &value));                        push(value);                    }                    break;                case 'O':                    pop();                    break;                case 'A':                    get_top();                    break;                default: break;            }        }        printf("\n");    }    return 0;}

括号匹配问题,用STL

#include<stdio.h>#include<stack>#include<string.h>using namespace std;stack<int> S;//重点:栈中只存放左括号,一遇到右括号就出栈 char str[110];char ans[110];int main(){    while(scanf("%s", str) != EOF)    {        int i;        for(i = 0; i < strlen(str); i ++)        {            if(str[i] == '(')            {                S.push(i); //将其数组下标放到堆栈中                 ans[i] = ' ';            }            else if(str[i] == ')')            {                if(S.empty()) ans[i] = '?';                else                {                    S.pop();                    ans[i] = ' ';                }            }            else ans[i] = ' ';        }        while(!S.empty())        {            ans[S.top()] = '$';            S.pop();         }        puts(str);        puts(ans);    }    return 0;}