Answer to Question #226773 in Python for Rahul

Question #226773
There is a singly linked list represented by the following structure:
struct Node int data;
struct Node* next;
Implement the following function:
struct Node
DeleteNodes (struct Node* head);
The function accepts a pointer to the start of the linked list, 'head' argument. Delete all such nodes from the input list whose adjacent on the right side has greater value and return the modified linked list. Note: . Return null if the list is empty (Incase of python if the list is No return None). Do not create a new linked list, just modify the input linked list an . return it. Example: Input: head: 6->2->5->4->9->7->2>1>5->9 Output: 65-9->7->2->9 Explanation: Node '2' is deleted as '2' < '5' then '4' is deleted as '4' < '9' then '1' deleted as '1' < '5' then '5' is deleted as '5' < '9'. Sample Input head: 9- 5 - 6 - 2 -> 7 Sample Output​
1
Expert's answer
2021-08-17T12:54:42-0400
#include<stdio.h>
#include<stdlib.h>


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


int size(struct Node* newNode){
int count=0;


while(newNode!=NULL){
newNode = newNode->next;
count++;
}
return count;
}


void push(struct Node** head1, int item){


struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));


newNode->data = item;
newNode->next = *head1;




*head1 = newNode; 
}


void delete(struct Node** head1, int position)
{
struct Node* tempData = *head1;
struct Node* prev;


//Deleting the head node if needed
int s = size(*head1);


if(position<1 || position>s){
printf("Invalid position\n");


return;
}
if(position==1)
{


*head1 = tempData->next; 






free(tempData);
return;
}




while (--position) 
{ 


prev = tempData; 
tempData = tempData->next; 
}






prev->next = tempData->next;




free(tempData);


}


void displayList(struct Node* newNode){




while(newNode!=NULL)
{
printf("%d->",newNode->data);
newNode = newNode->next;
}
printf("\n\n");
}
void DeleteNodes(struct Node* head1){
	struct Node* head2 =  head1;
	int count=0;
    int i = 1;
while(head1!=NULL){
int m = head1->data;
head1 = head1->next;
int n = head1->data;
head1 = head1->next;
if(m<n){
	delete(head1,i);
}
printf("%d->",head1->data);


i++;
count++;
}
while(head2 != NULL){
printf("%d->",head2->data);	
head2 = head2->next;
}


printf("\n\nCount is\t%d\n",count);


}
int main()
{
struct Node* head = NULL;




push(&head,9);
push(&head,5);
push(&head,1);
push(&head,2);
push(&head,7);
push(&head,9);
push(&head,4);
push(&head,5);
push(&head,2);
push(&head,6);




















printf("\nSample input\n");
displayList(head);
printf("\nSample output\n");
DeleteNodes(head);






return 0; 
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS