2 链式存储栈
1. 若是栈中元素的数目变化范围较大或不清楚栈元素的数目,就应该考虑使用链式存储结构。人们将用链式存储结构表示的栈称作"链栈"。链栈通常用一个无头结点的单链表表示。
参考文档:
http://blog.csdn.net/hguisu/article/details/7674195
大话数据结构
2. 代码
1 typedef struct StackNode 2 { 3 int data; 4 struct StackNode *next; 5 }StackNode,*LinkStackPtr; 6 7 typedef struct LinkStack 8 { 9 LinkStackPtr top; 10 int count; 11 }LinkStack; 12 13 //1. 初始化 14 LinkStack* init_linkStack() 15 { 16 LinkStack *s2=(LinkStack*)malloc(sizeof(LinkStack)); 17 s2->top=NULL; 18 s2->count=0; 19 return s2; 20 } 21 22 //2. 入栈 23 int push_linkStack(LinkStack*s2,int &e) 24 { 25 LinkStackPtr node=(LinkStackPtr )malloc(sizeof(StackNode)); 26 node->data=e; 27 node->next=s2->top; 28 s2->top=node; 29 //cout<<s2->count; 30 s2->count++; 31 32 return 0; 33 } 34 35 //3. 出栈 36 int pop_linkStack(LinkStack*s2) 37 { 38 LinkStackPtr node=NULL; 39 //cout<<s2->top; 40 //cout<<s2->count; 41 if(s2->count==0) 42 return -1; 43 int a=s2->top->data; 44 s2->top=s2->top->next; 45 s2->count--; 46 47 48 49 return a; 50 } 51 52 //4. 遍历 53 int print_linkStack(LinkStack*s2) 54 { 55 LinkStack *ss=s2; 56 LinkStackPtr node=ss->top; 57 int k=ss->count; 58 while(k>0) 59 { 60 printf(" %5d",s2->top->data); 61 ss->top=ss->top->next; 62 k--; 63 } 64 return 0; 65 }
3. 测试代码
1 int main() 2 { 3 LinkStack *s2; 4 int elem=0; 5 int ret=0; 6 int t1=11; 7 int t2=12; 8 int t3=13; 9 int t4=14; 10 int t5=15; 11 12 //1. 初始化 LinkStack* init_linkStack() 13 s2=init_linkStack(); 14 //cout<<s2->count; 15 16 //2. 入栈int push_linkStack(LinkStack*s2,int e) 17 printf("\n入栈:\n"); 18 ret=push_linkStack(s2,t1); 19 printf("%5d",s2->top->data); 20 ret=push_linkStack(s2,t2); 21 printf("%5d",s2->top->data); 22 ret=push_linkStack(s2,t3); 23 printf("%5d",s2->top->data); 24 ret=push_linkStack(s2,t4); 25 printf("%5d",s2->top->data); 26 ret=push_linkStack(s2,t5); 27 printf("%5d",s2->top->data); 28 29 //cout<<s2->top; 30 //3. 遍历int print_linkStack(LinkStack*s2) 31 //ret=print_linkStack(s2); 32 33 //4, 出栈 int pop_linkStack(LinkStack*s2,int &e) 34 printf("\n出栈:\n"); 35 elem=pop_linkStack(s2); 36 printf(" %5d",elem); 37 elem=pop_linkStack(s2); 38 printf(" %5d",elem); 39 elem=pop_linkStack(s2); 40 printf(" %5d",elem); 41 elem=pop_linkStack(s2); 42 printf(" %5d",elem); 43 elem=pop_linkStack(s2); 44 printf(" %5d",elem); 45 46 47 cout<<endl<<"hello"; 48 system("pause"); 49 return 0; 50 }
4. 测试结果