Monday, March 14, 2011

Given a linked list, remove all the nodes which have a greater value on right side. Eg the list 12->15->10->11->5->6->2->3

Given a linked list, remove all the nodes which have a greater value on right side.

Eg the list 12->15->10->11->5->6->2->3

should be changed to 15->11->6->3


#include
#include

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

void push(struct node **head_ref, int new_data)
{
struct node *new_node=(struct node *)malloc(sizeof(struct node));
new_node->data=new_data;
new_node->next=*head_ref;
*head_ref=new_node;
}

void reverseList(struct node **headref)
{
struct node *current=*headref;
struct node *prev=NULL;
struct node *next;
while(current!=NULL)
{
next=current->next;
current->next=prev;
prev=current;
current=next;
}
*headref= prev;
}

void printList(struct node *head)
{
while(head!=NULL)
{
printf("%d ",head->data);
head=head->next;
}
printf("\n");
}

void delLesserNodes(struct node *head)
{
struct node *current=head;
struct node *maxnode=head;
struct node *temp;
while(current!=NULL&¤t->next!=NULL)
{
if(current->next->datadata)
{
temp=current->next;
current->next=temp->next;
free(temp);
}
else
maxnode=current=current->next;

}
}

int main()
{
struct node *head=NULL;

push(&head,3);
push(&head,2);
push(&head,6);
push(&head,5);
push(&head,11);
push(&head,10);
push(&head,15);
push(&head,12);

reverseList(&head);
delLesserNodes(head);
reverseList(&head);

printList(head);
getchar();
return 0;
}

No comments :