栈的应用---用栈计算逆波兰表达式

#include<stdio.h>
#include<stdlib.h>
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;

struct Node{
    int Ele;
    PtrToNode Next;
};

Stack
CreateStack( void )
{
    Stack S;
    S = malloc( sizeof( struct Node ) );
    if(S == NULL )
        printf("out of space");
    S->Next = NULL;
    return S;
}
void
Push(int ch,Stack S)
{
    PtrToNode TmpCell;
    TmpCell = malloc(sizeof( struct Node ));
    if(TmpCell == NULL)
        printf("out of space ");
    else
    {
        TmpCell->Next = S->Next;
        S->Next = TmpCell;
        TmpCell->Ele = ch;
    }
}
int
IsEmpty(Stack S)
{
    return S->Next == NULL;
}
void
Pop( Stack S )
{
    PtrToNode TmpCell;
    TmpCell = S->Next;
    S->Next = TmpCell->Next;
    free(TmpCell);
}
int
Top( Stack S )
{
    return S->Next->Ele;
}

int main()
{
    char Tmp;
    int val1,val2,fin;
    Stack S;
    S = CreateStack();
    while( ( Tmp = getchar() ) != '\n' )
    {
        if(Tmp == ' ')
            continue;
        if(Tmp >= '0' && Tmp <= '9')
            Push( Tmp - '0',S );
        else if(Tmp == '+')
        {
            val1 = Top( S );
            Pop( S );
            val2 = Top( S );
            Pop( S );
            fin = val1 + val2;
            Push(fin, S );
        }
        else if( Tmp == '-' )
        {
            val1 = Top( S );
            Pop( S );
            val2 = Top( S );
            Pop( S );
            fin = val1 - val2;
            Push(fin, S );
        }
        else if( Tmp == '*' )
        {
            val1 = Top( S );
            Pop( S );
            val2 = Top( S );
            Pop( S );
            fin = val1 * val2;
            Push(fin, S );
        }
        else
        {
            val1 = Top( S );
            Pop( S );
            val2 = Top( S );
            Pop( S );
            fin = val1 / val2;
            Push(fin, S );
        }
    }
    printf("%d",Top( S ));
    return 0;
}
View Code

算法思想:遇到数字就进栈,遇到+ - * / 就出栈两个元素计算,再压入栈中

posted @ 2015-07-02 16:00  Gabyler  阅读(576)  评论(1编辑  收藏  举报