您的位置:首页 > 其它

链栈实现10进制转换2进制

2009-10-11 18:36 543 查看
#include<stdio.h>

#include<stdlib.h>

#include<malloc.h>

typedef int datatype;

typedef struct node{

datatype data;

struct node *next;

}linkstack;

void push(linkstack *s,datatype x){//元素入栈函数

linkstack *p;

p=(linkstack *)malloc(sizeof(linkstack));

p->data=x;

p->next=s->next;

s->next=p;

}

int pop(linkstack *top,int *x) //将x弹出链栈top并将值送入x中

{

linkstack *temp;

temp=top->next;

if(top->next==NULL)

return(0);

else

{

*x=temp->data;

top->next=temp->next;

free(temp);

return(1);

}

}

void main()

{

datatype e,n;int i=0;int j=0;

linkstack *q;

q=(linkstack *)malloc(sizeof(linkstack));

if (q==NULL) exit(0);

scanf("%u",&n);

while(n) // 当n不等于0

{push(q,n%2); // 入栈n除以2的余数(2进制的低位)

i++; // 统计入栈元素个数

n=n/2;

}

while(j<i) // 输出二进制

{ j++;

pop(q,&e);

printf("%d",e);

}

system("pause");

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: