Skip to content

Instantly share code, notes, and snippets.

@outlinepix
Created August 17, 2022 08:36
Show Gist options
  • Save outlinepix/10dc1e02016acc9b5adc130ac4fd5209 to your computer and use it in GitHub Desktop.
Save outlinepix/10dc1e02016acc9b5adc130ac4fd5209 to your computer and use it in GitHub Desktop.
Bubble sort on Linked List by values in C language.
/* full implimentationof Linked List : https://github.com/outlinepix/LinkedList */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
typedef struct Node
{
int data;
struct Node *next;
} Node;
typedef struct LinkedList_int
{
Node *head;
Node *next;
size_t length;
void (*print)(struct LinkedList_int *);
void (*push)(struct LinkedList_int *, int);
} LinkedList_int;
struct LinkedList_int *constructer()
{
LinkedList_int *list = (LinkedList_int *)malloc(sizeof(LinkedList_int));
list->head = NULL;
list->next = NULL;
list->length = 0;
return list;
}
struct Node *createNode(int data)
{
Node *node = (Node *)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
return node;
}
void insertNodeInt(LinkedList_int *list, int data)
{
Node *node = createNode(data);
if (list->head == NULL)
{
list->head = node;
list->next = node;
}
else
{
list->next->next = node;
list->next = node;
}
list->length += 1;
}
void bubbleSort(LinkedList_int *list)
{
for (Node *current = list->head; current; current = current->next) /* starts with head and itrate till NULL value*/
{
for (Node *nextNode = current->next; nextNode; nextNode = nextNode->next) /* starts with head and itrate till NULL value*/
{
if (current->data > nextNode->data)
{
int temporary = nextNode->data;
nextNode->data = current->data;
current->data = temporary;
}
}
}
}
void print(LinkedList_int *list)
{
if (list->head == NULL)
{
printf("Empty list\n");
return;
}
else
{
Node *current = list->head;
for (int i = 0; i < list->length; i++)
{
printf("[%d]. %d \n", i + 1, current->data);
current = current->next;
}
}
}
int main(void)
{
LinkedList_int *list = constructer ();
insertNodeInt(list, 60);
insertNodeInt(list, 40);
insertNodeInt(list, 30);
print(list);
printf("-----------------------\n");
printf("sorted LinkedList.\n");
bubbleSort(list);
print(list);
}
/* full implimentationof Linked List : https://github.com/outlinepix/LinkedList */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment