#include <stdio.
h>
#include <stdlib.h>
// Structure for a node in a linked list
struct node {
int data;
struct node *next;
};
// Global pointers to track the head and tail of the list
struct node *head = NULL, *tail = NULL;
// Function to insert n nodes at the end of the list
void insertNodeList(int n) {
int num, i;
struct node *newnode;
for (i = 1; i <= n; i++) {
newnode = (struct node *)malloc(sizeof(struct node));
if (newnode == NULL) {
printf("Memory cannot be allocated.\n");
return;
}
printf("Input data for node %d: ", i);
scanf("%d", &num);
newnode->data = num;
newnode->next = NULL;
if (head == NULL) {
head = newnode;
tail = newnode;
} else {
tail->next = newnode;
tail = newnode;
}
}
}
// Function to display the linked list
void displayList() {
struct node *tmp;
if (head == NULL) {
printf("List is empty.\n");
} else {
tmp = head;
while (tmp != NULL) {
printf("Data = %d\n", tmp->data);
tmp = tmp->next;
}
}
}
// Function to sort the linked list in ascending order
void sortList() {
struct node *prev, *curr;
int temp;
for (prev = head; prev != NULL; prev = prev->next) {
for (curr = prev->next; curr != NULL; curr = curr->next) {
if (prev->data > curr->data) {
temp = curr->data;
curr->data = prev->data;
prev->data = temp;
}
}
}
}
int main() {
int n;
printf("Enter number of nodes to insert: ");
scanf("%d", &n);
insertNodeList(n);
printf("\nLinked List before sorting:\n");
displayList();
sortList();
printf("\nLinked List after sorting:\n");
displayList();
return 0;
}