Delete nodes having greater value on right

PROBLEM :

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

Input:
You have to complete the method which takes 1 argument: the head of the  linked list  .You should not read any input from stdin/console. There are multiple test cases. For each test case, this method will be called individually.

Output:
Your function should return a pointer to the linked list in which all nodes which have a greater value on right side are removed.

Constraints:
1<=T<=50
1<=size of linked list <=100
1<=element of linked list <=1000

Example:

Input:
3
8
12 15 10 11 5 6 2 3
6
10 20 30 40 50 60
6
60 50 40 30 20 10

Output:

15 11 6 3
60
60 50 40 30 20 10

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/*

The structure of linked list is the following

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

*/

struct Node* reverse(struct Node *) ;

Node *compute(Node *head)
{
    head=reverse(head) ;
    struct Node *temp,*ptr ;
    temp=head ;
    int max=temp->data ;  
    while(temp->next!=NULL)
    {
        if(temp->next->data<max)
        {
            ptr=temp->next ;
            temp->next=ptr->next ;
            free(ptr) ;
        }
        else if(temp->next->data>max)
            max=temp->next->data ;
        else
            temp=temp->next ;
    }
    head=reverse(head) ;
    return head ;
}

struct Node* reverse(struct Node *head)
{
    if(head==NULL)
    return head ;
   
    if(head->next==NULL)
    return head;
   
    struct Node *one,*two,*third ;
    one=head ;
    two=one->next ;
    third=two->next ;
   
    one->next=NULL ;
    two->next=one ;
   
    while(third!=NULL)
    {
        one=two ;
        two=third ;
        third=third->next ;
       
        two->next=one ;
    }
    return two ;
   
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )