無極 發問時間: 電腦與網際網路程式設計 · 1 0 年前

push, pop, empty, stacktop寫出程式

寫出一完整之stack程式, 需滿足下列要求

1. Stack大小為3, 為char形態

2. 包含push, pop, empty, stacktop 等四個指令, 並於指令輸入完之後印出stack內的值(pop, stacktop指令需加印輸出值; empty需加印出TRUE(1) or FALSE(0)).

3. 要可以持續輸入指令(push,pop,empty,stacktop)

4. 當stack overflow或underflow時印出錯誤訊息, 並跳出執行

5. 使用VC++編譯.

依序執行下列指令, 每執行完一個指令, 將程式的ouput印出.

empty(s)  push(s,’A’)  push(s,’B’)  push(s,’C’)  x=stacktop(s)  empty(s)  y=pop(s)  push(s,’D’)  push(s,’E’)

2 個解答

評分
  • gary
    Lv 4
    1 0 年前
    最佳解答

    用 VS 2005 寫的:

    #include <iostream>

    using namespace std;

    const int max_stacks = 3;

    typedef struct

    {

    int top;

    char stack[max_stacks];

    } STACK;

    void initstack(STACK &s)

    {

    s.top = -1;

    }

    bool empty(STACK &s)

    {

    return (s.top == -1);

    }

    void push(STACK &s, const char c)

    {

    if (s.top >= max_stacks - 1)

    {

    cout << "Stack full" << endl;

    return;

    }

    s.stack[++s.top] = c;

    }

    char pop(STACK &s)

    {

    if (empty(s))

    {

    cout << "Stack empty" << endl;

    return '\0';

    }

    return s.stack[s.top--];

    }

    char stacktop(STACK &s)

    {

    return s.stack[s.top];

    }

    void printstack(STACK &s)

    {

    cout << "[top] ";

    for (int i = s.top; i>=0; i--)

    cout << s.stack[i] << " ";

    cout << "[bottom]" << endl;

    }

    int main()

    {

    STACK s;

    char x, y;

    initstack(s);

    cout << "empty? ";

    if (empty(s))

    cout << "TRUE" << endl;

    else

    cout << "FALSE" << endl;

    printstack(s);

    cout << "push: A" << endl;

    push(s, 'A');

    printstack(s);

    cout << "push: B" << endl;

    push(s, 'B');

    printstack(s);

    cout << "push: C" << endl;

    push(s, 'C');

    printstack(s);

    cout << "stack top: " << (x = stacktop(s)) << endl;

    printstack(s);

    cout << "empty? ";

    if (empty(s))

    cout << "TRUE" << endl;

    else

    cout << "FALSE" << endl;

    printstack(s);

    cout << "pop: " << (y = pop(s)) << endl;

    printstack(s);

    cout << "push: D" << endl;

    push(s, 'D');

    printstack(s);

    cout << "push: E" << endl;

    push(s, 'E');

    printstack(s);

    system("pause");

    return 0;

    }

    執行結果:

    empty? TRUE

    [top] [bottom]

    push: A

    [top] A [bottom]

    push: B

    [top] B A [bottom]

    push: C

    [top] C B A [bottom]

    stack top: C

    [top] C B A [bottom]

    empty? FALSE

    [top] C B A [bottom]

    pop: C

    [top] B A [bottom]

    push: D

    [top] D B A [bottom]

    push: E

    Stack full

    [top] D B A [bottom]

    2007-10-25 12:21:05 補充:

    剛剛發現有人問一樣的問題

    應該是你同學吧?

    參考資料: 自己
    • Commenter avatar登入以對解答發表意見
  • 1 0 年前

    上面的又不能用~

    還不是自己做出來了..

    要的話寄信跟我要吧

    • Commenter avatar登入以對解答發表意見
還有問題?馬上發問,尋求解答。