Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Saturday, January 6, 2018

Delete nodes having greater value on right


Idea is to reverse LL and maintain a max variable for link

 Node Reverse(Node head) {
Node prev=null;
    Node next=null;
    Node cur=head;
    while(cur!=null)
    {
        next=cur.next;
        cur.next=prev;
        prev=cur;
        cur=next;
       
    }
    head = prev;
        return head;
}
    void compute(LinkedList l)
    {
 Node r=Reverse(l.head);
 int max=r.data;
 Node cur=r;
 while(cur.next!=null)
 {
     if(cur.next.data<max)
     cur.next=(cur.next!=null)?cur.next.next:null;
     else
     {max=cur.next.data;
         cur=cur.next;}
 }
  l.head=Reverse(r);
    }
}
  
  // method 2 Recursive
  Node *compute(Node *head)
{ if(head->next==NULL)
return head;
struct Node *temp=compute(head->next);
if(temp->data > head->data)
return temp;
else
head->next=temp;
return head;
}

0 Comments:

Post a Comment

Stats