KEMBAR78
Sortinglist | PDF
0% found this document useful (0 votes)
6 views2 pages

Sortinglist

The document contains a C program that implements a linked list with functionalities to insert nodes, display the list, and sort the list in ascending order. It defines a structure for nodes and uses global pointers to manage the head and tail of the list. The main function orchestrates user input for node creation, displays the list before and after sorting.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Sortinglist

The document contains a C program that implements a linked list with functionalities to insert nodes, display the list, and sort the list in ascending order. It defines a structure for nodes and uses global pointers to manage the head and tail of the list. The main function orchestrates user input for node creation, displays the list before and after sorting.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

#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;
}

You might also like