Tuesday, April 19, 2011

WAP to Populate The next Higher in Singly Linked List

struct node
{
int data;
struct node *next;
struct node *next_larger;
}

initially next_larger of every node is point to NULL.
now write a c code which set all node's next_larger pointer.
where next_largest point to the next larger then its own value and largest value node's next_larger pointer points to NULL

i.e.
if LL is 3->1->5->6->4
then 3's next_larger points to 4
and 1's next_larger points to 3
and 5's next_larger points to 6
and 6's next_larger points to NULL
and 4's next_larger points to 5

#include
#include


struct node
{

int data;
struct node *next;
struct node *next_higher;

};

struct node* setNextHigher(struct node** head)
{
if(head==NULL)
return NULL;

struct node *start=*head;

(*head)=(*head)->next;

while((*head))
{

if((*head)->datadata)
{

(*head)->next_higher=start;
start= (*head);

}
else
{
struct node *p=start;
while(p->next_higher&&(*head)->data>=p->next_higher->data)
p=p->next_higher;

(*head)->next_higher=p->next_higher;
p->next_higher=(*head);

}
(*head)= (*head)->next;
}

return start;
}

void push(struct node** head_ref, int new_data)
{
/* allocate node */
struct node* new_node =
(struct node*) malloc(sizeof(struct node));

/* put in the data */
new_node->data = new_data;

/* link the old list off the new node */
new_node->next = (*head_ref);

/* move the head to point to the new node */
(*head_ref) = new_node;
}

/* Function to print linked list */
void printList(struct node *node)
{
while(node != NULL)
{
printf("%d ", node->data);
node = node->next_higher;
}
}

int main()
{
/* Start with the empty list */
struct node* head = NULL;

push(&head, 4);
push(&head, 6);
push(&head, 5);
push(&head, 1);
push(&head, 3);

head=setNextHigher(&head);

printList(head);

getchar();
}


Run Here https://ideone.com/fARV8

No comments :