栈的链式存储结构以及实现
1 #include "stdafx.h" 2 #include <iostream> 3 #include <exception> 4 using namespace std; 5 6 //栈的链式存储结构及实现 7 //栈的结构定义 8 #define OK 1 9 #define ERROR 0 10 #define TRUE 1 11 #define FALSE 0 12 typedef int sElemType; 13 typedef int Status; 14 15 16 typedef struct StackNode 17 { 18 sElemType data; 19 struct StackNode *next; 20 }StackNode,*LinkStackPtr; 21 22 typedef struct LinkStack 23 { 24 LinkStackPtr top; 25 int count; 26 }linkStack; 27 28 //栈空 29 Status StackEmpty(LinkStack *S) 30 { 31 if(S->count == 0) 32 { 33 return TRUE; 34 } 35 else 36 { 37 return FALSE; 38 } 39 40 } 41 //入栈 42 Status Push(LinkStack *S,sElemType e) 43 { 44 LinkStackPtr s = (LinkStackPtr)malloc(sizeof(StackNode)); 45 s->data = e; 46 s->next = S->top; 47 S->top = s; 48 S->count++; 49 return OK; 50 } 51 //出栈 52 Status Pop(LinkStack *S,sElemType *e) 53 { 54 if(StackEmpty(S)) 55 { 56 cout<<"栈空"<<endl; 57 return ERROR; 58 } 59 LinkStackPtr p = S->top; 60 S->top = p->next; 61 *e = p->data; 62 free(p); 63 S->count--; 64 return OK; 65 } 66 67 68 int _tmain(int argc, _TCHAR* argv[]) 69 { 70 int pushElem = 2; 71 linkStack *linkSt=(linkStack*)malloc(sizeof(LinkStack)); 72 linkSt->count=0; 73 Push(linkSt,pushElem);//将2入栈 74 pushElem = 3; 75 Push(linkSt,pushElem);//将3入栈 76 int popElem = 0; 77 Pop(linkSt,&popElem);//出栈,结果输出给popElem 78 cout<<popElem<<endl;//输出 出栈的元素 79 Pop(linkSt,&popElem);//出栈,结果输出给popElem 80 cout<<popElem<<endl;//输出 出栈的元素 81 Pop(linkSt,&popElem);//出栈,没有元素了.栈空 82 return 0 ; 83 }