Answer to Question #239542 in C for kanha

Question #239542

Write a C code to replace every element in a linked list with the next greatest element present in

the same list.


1
Expert's answer
2021-09-20T03:41:42-0400
#include<stdio.h>
struct LinkedList{
	int data;
	struct LinkedList *next;
};




void push(struct LinkedList** head, int data)
{
    
    struct LinkedList* new_node = (struct LinkedList*) malloc(sizeof(struct LinkedList));
  
    
    new_node->data  = data;
  
   
    new_node->next = (*head);
  
    
    (*head)    = new_node;
}




void nextGreatestElement(int arr[], int n)
{
	int x;
  
  int max =  arr[n-1];
 
  
  arr[n-1] = -1;
 
 
  for(x = n-2; x >= 0; x--)
  {
    
    int tempArray = arr[x];
 
    
    arr[x] = max;
 
    
    if(max < tempArray)
       max = tempArray;
  }
}


void printList(int arr[], int n)
{
  int x;
  for (x=0; x < n; x++)
    printf("%d ", arr[x]);
  printf("\n");
}
 
void  convertLinkedListToArray(struct LinkedList *head){
	
	struct LinkedList *temp  = head;
	int length = 0;
	while(temp != NULL){
		
		int item =  temp->data;
		length++;
		temp = temp->next;
	}
	
	struct LinkedList *tempNode  = head;
	int arr[length];
	int i = 0;
	while(tempNode != NULL){
			int item =  tempNode->data;
		arr[i] = item;
		i++; 
		tempNode = tempNode->next;
	}
	nextGreatestElement(arr, length);
	printList(arr, length);
}


void printList1(struct LinkedList *head){
	
	struct LinkedList *temp  = head;
	
	while(temp != NULL){
		
		printf("%d  ", temp->data);
		temp = temp->next;
	}
}






int main(){
struct 	LinkedList *list = NULL;
	push(&list, 10);
	push(&list, 1);
	push(&list, 2);
	push(&list, 12);
	push(&list, 3);
	push(&list, 7);
	push(&list, 4);
	printf("\nList before replacement of any element\n");
	printList1(list);
	printf("\nList after replacement of any element\n");
	convertLinkedListToArray(list);
	
}

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