Binary Equivalent Of Decimal Number Using Linked list

anurag_pareek 0 Tallied Votes 588 Views Share

In this program i had just extracted the modulo of the number given,and keep on adding it in linklist. later on,i reversed the link list and displayed the result.
By:--

Anurag Pareek

/////////////////////////////////////////////////////////////////////
//////////////        Programmer : Anurag Pareek         ///////////
///////////////////////////////////////////////////////////////////

# include<stdio.h>
# include<alloc.h>
struct binary
{  int data;
	struct binary *link;
};
void append(struct binary **,int);
void reverse(struct binary**);
void display(struct binary *);
void main()
{  int num,a;
	struct binary *p;
	p=NULL; /* empty list */
	printf("Enter Any Number : ");
	scanf("%d",&num);
	while(num != 0)
	{  a=num % 2 ;
		append(&p,a);
		num /=2;
	}
	reverse(&p);
	printf("The Binary Equivalent is : ");
	display(p);
}

void append(struct binary **q,int num)
{   struct binary *temp,*r;
	 temp = *q;
	 if(*q==NULL)
	 {   temp = (struct binary *)malloc(sizeof(struct binary));
		  temp->data=num;
		  temp->link=NULL;
		  *q=temp;
	 }
	 else
	 {  temp = *q;
		 while(temp->link !=NULL)
		 {  temp=temp->link;
		 }
		 r = (struct binary *)malloc(sizeof(struct binary));
		 r->data=num;
		 r->link=NULL;
		 temp->link=r;
	 }
}


void reverse(struct binary **x)
{ struct binary *q,*r,*s;
  q = *x;
  r=NULL;
  while(q !=NULL)
  {  s=r;
	  r=q;
	  q=q->link;
	  r->link=s;
  }
  *x=r;
}

void display(struct binary *q)
{  while(q!=NULL)
	{ printf("%d",q->data);
	  q=q->link;
	}
}
Kellaw 0 Newbie Poster

How do you do it using stack?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.