# Linked Lists

0 votes
242 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.

in DS
edited
1
$val2 = 2*val2 + p\rightarrow data;$
0
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$

edited by
0
Thanks for the perfect answer...
0
Well explained !

## Related questions

1 vote
0 answers
1
196 views
0 votes
1 answer
2
301 views
You're entrusted with the task of deleting a node in a singly linkedlist, whose data field is 'x'. Note that, the node which is to be deleted can be at any arbitrary position in the linked list. Consider the following scenarios. S1. You're only provided ... provided with a pointer to the starling node of the linked list. Which of the following options is correct? How deletion possible with S2?
1 vote
1 answer
3
254 views
Consider the following statements about free space management I) Bit vectors are inefficient unless the entire vector is kept in main memory. II) Linked list approach requires less I/O time. III) Linked list approach is more efficient than bit vectors in terms of storage space. Which of the following statements is/are TRUE:?
1 vote
1 answer
4
262 views
Consider the following Linked list Node structure struct Node { int data; struct Node * next; } typedef struct Node Node; Consider the following function to reverse the singly linked list Node* reverse_list(Node *head) { Node *temp = NULL; Node *next ; while(head) { next = 1)------; ... at 1 and 2 respectively (A) head, head->next (B) head->next,head (C) NULL, head->next (D) head->next, next