2014年2月19日 星期三

C++基本的Stack


  • Interface: push, pop, peek


  • 實作上皆必須是O(1)
  • dtor可以呼叫pop來實作
  • 利用Node之linked-list來實作Stack
  • 動態記憶體配置必須小心memory leak, i.e., 別忘記de-allocate
C ++ code:


#include <iostream>
using namespace std;

class Node{
public:
    Node( ):val(0), next(NULL){}
    int val;
    Node *next;
};

class Stack{
public:
    Stack( );
    virtual ~Stack( );
    void push( int );
    int pop();
    int peek() const;
    void showElements( ) const;
private:
    Node *top;
};

Stack::Stack( ) : top(NULL){
}

Stack::~Stack( ){
    cout << "dtor: \n";
    while( top != NULL ){
        int v = this->pop();
        if( v != -1 )
            cout << "delete " << v << " ";
    }
}

void Stack::push(int value){
    Node *add = new Node;
    add->val = value;
    add->next = top;
    top = add;
}

int Stack::pop( ){
    if( top == NULL )
        return -1;
    else{
        Node *deleted = top;
        top = deleted->next;
        int r = deleted->val;
        delete deleted;
        return r;
    }
}

int Stack::peek() const{
    if( top == NULL )
        return -1;
    else{
        return top->val;
    }
}

void Stack::showElements( ) const{
    Node *current = top;
    while( current != NULL ){
        cout << current->val << " ";
        current = current->next;
    }
    cout << endl;
}



int main( ){
    Stack x;
    int cmd;
    while(true){
        cout << "1.push 2.pop 3.peek 4.show 5.exit: ";
        cin >> cmd;
        if( cmd == 5 )
            break;

        switch(cmd){
        case 1:
            cout << "push: ";
            int v;
            cin >> v;
            x.push(v);
            break;
        case 2:
            cout << "pop " << x.pop( );
            cout << endl;
            break;
        case 3:
            v = x.peek();
            if( v == -1 )
                cout << "No element!\n";
            else
                cout << "top element: " << x.peek();
            cout << endl;
            break;
        case 4:
            x.showElements( );
            break;
        default:
            break;
        }

    }
}


refine:
  1. Node可以寫成accessor, mutator 之方式
  2. Stack 可以多實作copy ctor, assignment operator

沒有留言:

張貼留言