水水的实现一下链式栈。
#include <cstdio> #include <iostream> #include <cstring> #include <cstdlib> using namespace std; typedef struct Sta { int data ; struct Sta *next ; }Stack ; void createStack(Stack *&s) //建立一个带头结点的链栈 { s = (Stack*)malloc(sizeof(Stack)) ; s->next = NULL ; printf("新栈创建成功 ") ; } void destroyStack(Stack *&s) //销毁一个链栈 { Stack *p = s ; Stack *q = s->next ; while(q != NULL) { free(p) ; p = q ; q = p->next ; } free(p) ; } int isEmpty(Stack *s) //判定 { return (s->next == NULL) ; } void pushStack(Stack *&s,int e) //将元素e进栈 { Stack *p ; p = (Stack*)malloc(sizeof(Stack)) ; p->data = e ; p->next = s->next ; s->next = p ; printf("%d已经入栈成功 ",e) ; } void popStack(Stack *&s,int &e) //出栈操作,并且将出栈的元素保存到e中 { Stack *p = s->next ; e = p->data ; s->next = p->next ; free(p) ; printf("出栈成功 ") ; } void getTop(Stack *&s,int &e) { if(s->next == NULL) { printf("栈为空,无法取得栈顶元素 ") ; return ; } else { e = s->next->data ; } } int main() { Stack *s ; createStack(s) ; pushStack(s,11) ; pushStack(s,12) ; if(isEmpty(s)) { printf("栈为空 ") ; }else { printf("栈不为空 ") ; } int popNum ; popStack(s,popNum) ; printf("出栈的元素为%d ",popNum) ; int top ; getTop(s,top) ; printf("栈顶元素是%d ",top) ; }