C++简单链栈实现

实现一个简单的C++链栈。

#include 

using namespace std;

typedef int elemType;
typedef struct stackNode {
    elemType data;
    struct stackNode *next;
} stackNode, *S;

bool initStack(S &s) {
    s = NULL;
    return true;
}

bool push(S &s, elemType e) {
    S p;
    p = new stackNode;
    if (!p) return false;
    p->data = e;
    p->next = s;
    s = p;
    return true;
}

bool pop(S &s, elemType &e) {
    if (!s) return false;
    S p;
    p = s;
    s = s->next;
    e = p->data;
    delete p;
    return false;
}

bool getTop(S s, elemType &e) {
    if (!s) return false;
    e = s->data;
    return true;
}

bool isEmpty(S s) {
    if (!s) return true;
    else return false;
}

int main() {
    S s;
    cout << "Init Stack." << endl;
    initStack(s);
    cout << "1";
    cout << "Push 1,2,3,4,5,6 ." << endl;
    for (int i = 1; i < 7; i++) {
        push(s, i);
    }
    cout << "Stack empty: " << isEmpty(s) << endl;
    cout << "Get top element of the Stack: ";
    int top;
    getTop(s, top);
    cout << top << endl;
    cout << "Pop all element from the Stack:";
    int e;
    while (!isEmpty(s)) {
        pop(s, e);
        cout << e << " ";
    }
    cout << endl;
    return 0;
}

Output:

Init Stack.
1Push 1,2,3,4,5,6 .
Stack empty: 0
Get top element of the Stack: 6
Pop all element from the Stack:6 5 4 3 2 1

你可能感兴趣的:(C++简单链栈实现)