GATE CSE
First time here? Checkout the FAQ!
x
0 votes
110 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)  
edited by | 110 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 Boss (8.4k points)  
edited by
Thanks for the perfect answer...
Well explained !

Related questions

0 votes
2 answers
1
+2 votes
1 answer
2
asked in DS by thor Boss (8.7k points)   | 165 views
0 votes
1 answer
3
asked in Programming by Shubhanshu Active (1.7k points)   | 38 views


Top Users Jun 2017
  1. Bikram

    3704 Points

  2. Hemant Parihar

    1484 Points

  3. junaid ahmad

    1432 Points

  4. Arnab Bhadra

    1408 Points

  5. Niraj Singh 2

    1311 Points

  6. Rupendra Choudhary

    1194 Points

  7. rahul sharma 5

    1120 Points

  8. Arjun

    930 Points

  9. srestha

    928 Points

  10. Debashish Deka

    896 Points

Monthly Topper: Rs. 500 gift card
Top Users 2017 Jun 19 - 25
  1. Bikram

    1960 Points

  2. Niraj Singh 2

    1306 Points

  3. junaid ahmad

    502 Points

  4. sudsho

    410 Points

  5. akankshadewangan24

    388 Points


23,355 questions
30,065 answers
67,365 comments
28,382 users