栈
栈
| Time Limit: 1000MS | Memory Limit: 65535KB |
| Submissions: 1021 | Accepted: 476 |
Sample Input
10
Sample Output
1010
解法一:链栈
# include<stdio.h>//链栈 # include<malloc.h> # define Len sizeof(struct node) # define N 100 typedef int ElemType; typedef struct node { ElemType data; struct node *next; }LinStack; void push(LinStack *s,ElemType e)//压入 { LinStack *p; p=(LinStack *)malloc(Len); p->data=e; p->next=s->next; s->next=p; } int pop(LinStack *top,ElemType *e)//弹出 { LinStack *p; p=top->next; if(p==NULL) return 0; *e=p->data; top->next=p->next; free(p); return 1; } int main() { LinStack *s; ElemType num,e; int count=0,i; s=(LinStack *)malloc(Len); scanf("%d",&num); while(num) { push(s,num%2); count++; num/=2; } for(i=0;i<count;i++) { pop(s,&e); printf("%d",e); } printf("\n"); return 0; }
解法二:顺序栈
# include<stdio.h>//顺序栈 # include<malloc.h> # define Len sizeof(struct node) # define N 100 typedef int ElemType; typedef struct node { ElemType data[N],top; }SeqStack; void InitStack(SeqStack *s) { s->top=-1; } SeqStack *push(SeqStack *s,ElemType e)//压入 { if(s->top==N-1)return 0; s->top++; s->data[s->top]=e; return s; } ElemType pop(SeqStack *s)//弹出 { ElemType e; e=s->data[s->top]; s->top--; return e; } int main() { SeqStack *s; ElemType num,e; int count=0,i; s=(SeqStack *)malloc(Len); scanf("%d",&num); InitStack(s); while(num) { push(s,num%2); count++; num/=2; } for(i=0;i<count;i++) { e=pop(s); printf("%d",e); } printf("\n"); return 0; }
浙公网安备 33010602011771号