c++实现链栈:
//链栈的实现 #include <iostream> #include <string> using namespace std; struct Data { public: int bookNum; Data * next; }; //链栈的初始化 Data* SeqStackInit() { Data *top = new Data; top = NULL; return top; } //链栈的判空 int SeqStackEmpty(Data* s) { if (NULL == s) { return true; } else return false; } //链栈的入栈 Data * SeqStackPush(Data* s, int x) { Data* s1 = new Data; s1->bookNum = x; s1->next = s; s = s1; cout<<"入栈元素:"<<s->bookNum<<endl; return s; } //链栈的出栈 Data * SeqStackPop(Data* s) { if (NULL != s) { int x; Data * p = new Data; p = s; x = s->bookNum; cout <<"出栈元素:"<<s->bookNum<<endl; s = s->next; delete(p); return s; } } //链栈中取出栈顶元素 int SeqStackGetTop(Data* s) { if (NULL != s) return s->bookNum; } //链栈的长度 int SeqStackLength(Data* s) { int length = 0; Data* s1 = s; //cout <<s->bookNum<<endl; while(NULL != s1) { length++; s1 = s1->next; } return length; } int main() { Data* s = SeqStackInit(); cout <<"判空操作:"<<SeqStackEmpty(s)<<endl; cout <<"入栈操作:"<<endl; s = SeqStackPush(s,12); s = SeqStackPush(s,23); s = SeqStackPush(s,4); s = SeqStackPush(s,78); s = SeqStackPush(s,3); cout <<"栈顶元素:"<<SeqStackGetTop(s)<<endl; cout <<"栈的长度:"<<SeqStackLength(s)<<endl; cout <<"出栈操作:"<<endl; s = SeqStackPop(s); cout <<"判空操作:"<<SeqStackEmpty(s)<<endl; cout <<"栈的长度:"<<SeqStackLength(s)<<endl; cout <<"栈顶元素:"<<SeqStackGetTop(s)<<endl; return 0; }