GATE CSE
First time here? Checkout the FAQ!
x
0 votes
135 views

Q)The below code returns decimal value of binary linked list
 

int val(struct Node *head)
{
    struct Node *p = head;
    int val2= 0;
    while (p!= NULL)
        {
            XYZ;//fill the contents of XYZ
            p = p→next;
        }
    return val2;
}


What is XYZ in above code ? Please provide a sound explaination too.

asked in DS by (427 points) 8 16
edited by | 135 views
$val2 = 2*val2 + p\rightarrow data;$
How ???

1 Answer

+3 votes
Best answer

In the given linked list we traverse starting from Head and ending at tail.

If it would be an array,then we simply start from $Ar\left [ n \right ]\, to\, Ar\left [ 1 \right ]$ and each time we would multiply with $2^{i}\, \, ,i=0,1,2\cdots \left ( n-1 \right )$,Like this

for(j=n,i=0;j>=1 & i<n;j--,i++)
{
    res=pow(2,i)*ar[j]+res;
}
printf("Equivalent value =%d",res);

But as in Linked list according to your question ,we cannot traverse from tail to head as you have not provided the length of linked list.so starting from head it can be done as-:

res=(res*2)+p->data;

         $OR$

res=(res<<1)+p->data

which is your $XYZ$

Example -:

$2*0+1\left ( p\rightarrow data\left ( 100 \right ) \right )=1$

$2*1+0\left ( p\rightarrow data\left ( 200 \right ) \right )=2$

$2*2+1\left ( p\rightarrow data\left ( 300 \right ) \right )=5$

$2*5+1\left ( p\rightarrow data\left ( 400 \right ) \right )=11$

answered by Veteran (13.4k points) 16 55 115
edited by
Thanks for the perfect answer...
Well explained !


Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
Top Users Oct 2017
  1. Arjun

    23398 Points

  2. Bikram

    17078 Points

  3. Habibkhan

    8280 Points

  4. srestha

    6300 Points

  5. Debashish Deka

    5438 Points

  6. jothee

    4978 Points

  7. Sachin Mittal 1

    4772 Points

  8. joshi_nitish

    4352 Points

  9. sushmita

    3970 Points

  10. Rishi yadav

    3804 Points


Recent Badges

Commentator Shivam Chauhan
Notable Question set2018
Nice Comment srestha
Notable Question set2018
Regular Shankar Jha
Popular Question Shubhanshu
Good Comment mcjoshi
Notable Question antarachoudhury
Popular Question shweta12345
Good Comment Rohan Mundhey
27,325 questions
35,177 answers
84,123 comments
33,280 users