IHYPRESS PROGRAMMING
Tutorials and C programs with code and output for beginners
c programming
HOME | ASP | C | CSS | GNUPLOT | HTML | JAVASCRIPT | PERL | PHP | PYTHON | RUBY | SVG
arrow_circle_left
share
arrow_circle_right
CAdvanced Programming : Ordered Linked List
<12.10>
#include <stdio.h> #include <stdlib.h> //node definition typedef struct NODE { int data; struct NODE *next; } node; //head and tail pointers of the linked list node *head; node *tail = NULL; //funtion that adds a new node to the list void addnode (int data) { //creates a new node node *newnode = (node *) calloc (1, sizeof (node)); newnode->data = data; newnode->next = NULL; //checks if list is empty if (head == NULL) { //if list is empty, both head and tail will point to new node head = newnode; tail = newnode; } else { tail->next = newnode; tail = newnode; } } //function to sort nodes of the list in ascending order void sortlist () { //current node will point to head node *current = head; node *index = NULL; int temp; //soft the list if it is not empty if (head == NULL) printf ("The list is not sorted. It is empty.\n"); else { while (current != NULL) { //index will point to node next to current index = current->next; while (index != NULL) { //if current node's data is greater than index's node data, swap the data between them if (current->data > index->data) { temp = current->data; current->data = index->data; index->data = temp; } index = index->next; } current = current->next; } } } //function to display all the nodes present in the list void display (void) { //node current will point to head node* current = head; if (head == NULL) { printf ("This list is empty."); } else while (current != NULL) { //travel the list and print each node printf ("%d ", current->data); current = current->next; } printf ("\n"); } int main (void) { //adds data to the list addnode (9); addnode (7); addnode (2); addnode (5); addnode (4); //displays the original list printf ("Original list > "); display (); //sorting the list sortlist (); //displays the sorted list printf ("Sorted list > "); display (); return (0); }
Hergestellt in Deutschland / Made in Germany
Original list > 9 7 2 5 4 Sorted list > 2 4 5 7 9
COPYRIGHT © 2015-2026 IHY PRESS Frankfurt am Main 60329 Deutschland