Skip to content

Instantly share code, notes, and snippets.

@Roytangrb

Roytangrb/list.c

Last active Nov 22, 2020
Embed
What would you like to do?
List struct and bubble sort
/*
* Bubble sort a list
* By RT
* 22 Nov, 2020
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct node {
int val;
struct node *next;
} node;
typedef node *list;
list create_list(int val) {
list l = malloc(sizeof(node));
l->val = val;
l->next = NULL;
return l;
}
list concat_list(list h1, list h2) {
list head = h1;
while (h1->next != NULL){
h1 = h1->next;
}
h1->next = h2;
return head;
}
void bubble_sort_list(int n, list l){
if (l == NULL) return;
for (int i = n - 1; i >= 0; i --){
list head = l;
for (int j = 0; j <= i; j++){
if (head->next != NULL && head->next->val < head->val){
int temp = head->val;
head->val = head->next->val;
head->next->val = temp;
}
head = head->next;
}
}
}
int main(void){
srand(time(NULL));
list l = create_list(rand() % 200);
//gen random numbers and build list
for (int i = 0; i < 99; i ++){
l = concat_list(create_list(rand() % 200), l);
}
//sort the list
bubble_sort_list(100, l);
//print in row of 5
int i = 0;
while (l != NULL){
printf("%-5d", l->val);
if (++i % 5 == 0) printf("\n");
l = l->next;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.