@kamakshi this code will work for every value except when your list has only one node.for that you will have to add check : p=head; q=head; if(p->link == NULL) printf("The middle element is %d",p->data); else { if(q->link->link!=NULL) {
p=p->link; q=q->link->link; } printf("The middle element is %d",p->data);
Given a Binary Tree, find vertical sum of the nodes that are in same vertical line. Print all sums through different vertical lines. Examples: 1 / \ 2 3 / \ / \ 4 5 6 7 The tree has 5 vertical lines Vertical-Line-1 has only one node 4 => vertical sum is 4 Vertical-Line-2: has only one node 2=> vertical sum is 2 Vertical-Line-3: has three nodes: 1,5,6 => vertical sum is 1+5+6 = 12 Vertical-Line-4: has only one node 3 => vertical sum is 3 Vertical-Line-5: has only one node 7 => vertical sum is 7 So expected output is 4, 2, 12, 3 and 7
p=head;
ReplyDeleteq=head;
if(q->next->next!=NULL)
{
p=p->next;
q=q->next->next;
}
printf("The middle element is %d",p->data);
There is a problem in the above code.It does not work if there is a single node,or there are odd no of nodes.
ReplyDeleteit should be like this:
int middle(struct node *head)
{
p=head;
q=head;
if(head->next==NULL)
return (p->data);
else
while(q->next->next!=NULL)
{
p=p->next;
if(q->next!=NULL)
q=q->next->next;
else
return (p->data);
}
return(p->data);
}
@kamakshi this code will work for every value except when your list has only one node.for that you will have to add check :
ReplyDeletep=head;
q=head;
if(p->link == NULL)
printf("The middle element is %d",p->data);
else
{
if(q->link->link!=NULL)
{
p=p->link;
q=q->link->link;
}
printf("The middle element is %d",p->data);