IHYPRESS.NET
C
HOME | ASP | C | CSS | HTML | JAVASCRIPT | PERL | PHP | PYTHON | RUBY | SVG
Earn Free Bitcoin
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 of the linked list node *head; node *tail = NULL; //adds a new node to the list void addnode (int data) { //Create 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; } } //sort nodes of the list in ascending order void sortlist () { //current node will point to head node *current = head; node *index = NULL; int temp; if (head == NULL) { exit (1); } 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; } } } //display all the nodes present in the list void display (void) { //node current will point to head node* current = head; if (head == NULL) { printf ("List is empty! \n"); exit(1); } 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); //Displaying original list printf ("Original list > "); display (); //Sorting list sortlist (); //Displaying 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-2024 IHYPRESS.NET. A DIVISION OF IHY PRESS. ALL RIGHTS RESERVED.