Time Limit:   1000MS       Memory Limit:   65535KB
Submissions:   1021       Accepted:   476

 

Description

建立顺序栈或链栈,编写程序实现十进制数到二进制数的转换。

Input

输入只有一行,就是十进制整数。

Output

转换后的二进制数。

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;
}

 

posted on 2012-05-30 21:59  即为将军  阅读(329)  评论(0)    收藏  举报

导航