天天看點

【大風】matrix:expression題目代碼分享

#include <stdio.h>
//大風的醜陋代碼 
int numberStack[]={};//初始化stack,第零位代表長度

//使用的資料結構:棧 
//使用的算法:将第一個數字扔進棧,然後接着讀取後面的數字。
//如果是加号相連,則把數字扔進棧,如果是乘号相連 ,則pop出棧中的一個數字,并相乘,再扔進棧。

//最後把棧中的數字全部相加得結果
void push (int newElement,int stack[])
{
    //不告訴你
    //Deadline 2017.1.1 ,慢慢想
}
int pop(int stack[])//若棧為空則傳回0
{
    //不告訴你
    //Deadline 2017.1.1 ,慢慢想
}

int main()

{
    int number;
    char opeChar;
    scanf("%d",&number);
    push(number % ,numberStack);
    while ( (opeChar = getchar() )!=EOF)
    {
        scanf("%d",&number);
            if (opeChar == '+')
            {
                push(number% ,numberStack);
            }
            if (opeChar =='*')//本次運算符是*
            {
                push( (pop(numberStack)*(number%)) % ,numberStack);   
            }

    }

    while (numberStack[]>)
    {
        push( ( pop(numberStack)+pop(numberStack) )  %,numberStack);
    }
    printf("%d\n",pop(numberStack));
}
           

comments:當然,本題不一定要用棧,隻是那時,我做這道題的時候剛好學了下棧的寫法,于是就拿來用了。

推薦大家看看偉元的代碼。

關于棧(stack)

In computer science, a stack is an abstract data type that serves as a collection of elements, with two principal operations: push, which adds an element to the collection, and pop, which removes the most recently added element that was not yet removed. The order in which elements come off a stack gives rise to its alternative name, LIFO (for last in, first out). Additionally, a peek operation may give access to the top without modifying the stack.

來源:wiki_stack

繼續閱讀