Write a ‘C’ program to sort elements of a singly linked list in ascending order and display the sorted List.
#include <stdio.h>
#include <stdlib.h>
// Structure of a singly linked list node
struct Node {
int data;
struct Node* next;
};
// Function to create a singly linked list
struct Node* createList(int n) {
struct Node *head = NULL, *temp = NULL, *newNode = NULL;
int value;
for(int i = 0; i < n; i++) {
printf("Enter value for node %d: ", i + 1);
scanf("%d", &value);
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
if(head == NULL) {
head = newNode;
temp = newNode;
} else {
temp->next = newNode;
temp = newNode;
}
}
return head;
}
// Function to display the list
void displayList(struct Node* head) {
if(head == NULL) {
printf("List is empty.\n");
return;
}
struct Node* temp = head;
while(temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
// Function to sort the linked list in ascending order
void sortList(struct Node* head) {
if(head == NULL) return;
struct Node *i, *j;
int temp;
for(i = head; i != NULL; i = i->next) {
for(j = i->next; j != NULL; j = j->next) {
if(i->data > j->data) {
temp = i->data;
i->data = j->data;
j->data = temp;
}
}
}
}
// Main function
int main() {
struct Node* head = NULL;
int n;
printf("Enter number of nodes: ");
scanf("%d", &n);
head = createList(n);
printf("Original List:\n");
displayList(head);
sortList(head);
printf("Sorted List in ascending order:\n");
displayList(head);
return 0;
}
