Write a C code to replace every element in a linked list with the next greatest element present in
the same list.
#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);
}
Comments
Leave a comment