C++简单链栈实现

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

#include <iostream>

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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容