标签:
元素的入栈出栈
链栈:
1 #include <iostream> 2 #include <cstdio> 3 using namespace std; 4 struct stack 5 { 6 char data; 7 stack *next; 8 }; 9 stack* initstack() /*为栈头指针申请内存*/ 10 { 11 stack *s=new stack; 12 s->next=NULL; 13 return s; 14 } 15 int isempty(stack *s) 16 { 17 if(s->next==NULL) 18 return 1; 19 return 0; 20 } 21 void pushstack(stack* s,char c) 22 { 23 stack *p=new stack; 24 p->next=s->next; 25 s->next=p; 26 p->data=c; 27 } 28 int popstack(stack *s,char *e) 29 { 30 if(isempty(s)) 31 return 0; 32 else 33 { 34 stack *p=s->next; 35 s->next=p->next; 36 *e=p->data; 37 delete p; 38 return 1; 39 } 40 } 41 int main() 42 { 43 stack *s=initstack(); 44 char c,e; 45 while(scanf("%c",&c)&&c!=‘\n‘) 46 pushstack(s,c); 47 while(!isempty(s)) 48 { 49 popstack(s,&e); 50 cout<<e; 51 } 52 }
顺序栈:
1 #include <iostream> 2 #include <cstdio> 3 using namespace std; 4 struct stack 5 { 6 char s[100]; 7 int top,bottom; 8 }; 9 void initstack(stack* st) 10 { 11 st->top=0; 12 st->bottom=0; 13 } 14 int isempty(stack *st) 15 { 16 if(st->top==st->bottom) 17 return 1; 18 return 0; 19 } 20 void pushstack(stack* st,char c) 21 { 22 st->top++; 23 st->s[st->top]=c; 24 } 25 int popstack(stack* st,char *e) 26 { 27 if(isempty(st)) 28 return 0; 29 *e=st->s[st->top]; 30 st->top--; 31 return 1; 32 } 33 int main() 34 { 35 stack q; 36 initstack(&q); 37 char c,e; 38 while(scanf("%c",&c)&&c!=‘\n‘) 39 pushstack(&q,c); 40 while(!isempty(&q)) 41 { 42 popstack(&q,&e); 43 cout<<e; 44 } 45 46 }
标签:
原文地址:http://www.cnblogs.com/a1225234/p/4676720.html