Problem description:
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 1argument: 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 shouldreturn a pointer to the linked list in which all nodes which have a greater value on right side are removed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
/* The structure of linked list is the following struct Node { int data; Node* next; }; */ Node *compute(Node *head) { // your code goes here int arr[150]; int idx=0; Node *tmp=head,*prev,*nNode; Node *root; // if(head->next==NULL) // return head; while(tmp) { prev=tmp; arr[idx++]=prev->data; tmp=tmp->next; } int mx=arr[idx-1]; root=new Node; root->data=arr[idx-1]; if(idx>=2) for(int i=idx-2;i>=0;i--) { if(arr[i]>=mx) { mx=arr[i]; nNode=new Node; nNode->data=mx; nNode->next=root; root=nNode; } } return root; } |