#include
#include
#define ElemType int
typedef struct{
ElemType e;
struct Node *next;
}Node,*pNode,**ppNode;//使用pNode表示一级指针,ppNode表示二级指针
//计算整数n的m次方
int pow2(int n,int m);
int getElemNum(pNode head);
pNode getLastElem(pNode head);
void push(ppNode head,ElemType e);
ElemType pop(ppNode head);
void showElem(pNode head);
pNode getElem(pNode head,int i);
int main(int argc, char *argv[])
{
printf("%d\n",changto2(10));
printf("%d\n",changto10(1010));
return 0;
}
int changto2(int n){
if(n<0) return -1;
if(n==0) return 0;
int i,j,k,sum=0;
pNode head=NULL;
while(n!=0){
i=n%2;
n=(n-i)/2;
push(&head,i);
}
k=getElemNum(head);
for(j=k;j>0;j--){
int t = pop(&head);
int x = pow2(10,j-1);
sum=t*x+sum;
}
return sum;
}
int pow2(int n,int m){
int sum=1,i=0;
for(i=0;i
sum=sum*n;
}
return sum;
}
int changto10(int n){
if(n<0) return -1;
if(n==0) return 0;
int i,j,k,sum=0;
pNode head=NULL;
while(n!=0){
i=n%10;
n=n/10;
push(&head,i);
}
k=getElemNum(head);
for(j=k;j>0;j--){
int t = pop(&head);
int x = pow2(2,j-1);
sum=t*x+sum;
}
return sum;
}
int getElemNum(pNode head){
if(!head) return 0;
pNode p=head;
int i=0;
while(p){
i++;
p=p->next;
}
return i;
}
pNode getLastElem(pNode head){
if(!head) return NULL;
pNode p=head;
while(p->next) p=p->next;
return p;
}
void push(ppNode head,ElemType e){
pNode node = (pNode)malloc(sizeof(Node));
node->e=e;
node->next=NULL;
if(!*head){
*head=node;
return;
}
pNode p;
p=getLastElem(*head);
p->next=node;
}
ElemType pop(ppNode head){
int n =getElemNum(*head);
ElemType e;
if(n<1) return;
if(n==1){
e=(*head)->e;
free(*head);
*head=NULL;
return e;
}
pNode p = getElem(*head,n-1);
pNode t=p->next;
e=t->e;
free(p->next);
p->next=NULL;
return e;
}
pNode getElem(pNode head,int i){
int n = getElemNum(head);
if(i<1 || i>n) return;
int j=1;
pNode p=head;
while(j
j++;
p=p->next;
}
return p;
}
void showElem(pNode head){
if(!head){
printf("empty link\n");
return;
}
pNode p =head;
int n =getElemNum(head);
printf("this link has %d elems\n",n);
while(p){
printf("%d ",p->e);
p=p->next;
}
printf("\n");
return;
}