Hi friends,
In this post I'll explain "how to convert a decimal number to binary equivalent using Linked list". Usually, we use array for this purpose, but arrays are created statically and memory wastage may occur. Linked list is a perfect solution for this as it is created dynamically and no there is no wastage of memory also.!!!!
Algorithm
- Initialize PREV_NODE and NODE as NULL.
- Input a number 'num'.
- if num<=0 go to step 9
- PREV_NODE=NODE
- add (num%2) to NODE->number
- NODE->next=PREV_NODE
- num=num/2
- go to step 3
- if NODE is NULL go to 13
- print NODE->number
- NODE=NODE->next
- go to step 9
- End
The complete code in C is given here:
#include<stdio.h>
struct binary {
int num;
struct binary *next;
};
struct binary* add( struct binary **curr, int n)
{
struct binary *temp;
temp=(struct binary *)malloc(sizeof(struct binary));
temp->num=n;
temp->next=*curr;
return temp;
}
int main()
{
int number, binary_num;
struct binary *head= NULL;
printf("ENTER A DECIMAL NUMBER : ");
scanf("%d",&number);
while(number>0)
{
binary_num=number%2;
head =add(&head,binary_num);
number/=2;
}
printf("EQUIVALENT BINRY NUMBER IS : ");
for(;head!=NULL;head=head->next)
printf("%d",head->num);
}
Friends, I hope this post will be useful to you..!!!
Your valuable suggestions are always welcomed..!!!!Comment it here.!!
2 comments :
maan gaye ustaad
@Anonymous thank you for your feedback.. Keep visiting.!!!!!!
Post a Comment