Skip to content

Instantly share code, notes, and snippets.

@muhammedeminoglu
Created May 20, 2017 23:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save muhammedeminoglu/4c7247ffb5834586fc2627b01f0fa7d4 to your computer and use it in GitHub Desktop.
Save muhammedeminoglu/4c7247ffb5834586fc2627b01f0fa7d4 to your computer and use it in GitHub Desktop.
This code shows you how to use linked list on bubble sort.
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
struct node* start = NULL;
//I dont want to traverse for add an item last position, i will use last->next
struct node* last = NULL;
struct node* temp;
struct node* createNode(int x)
{
struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = x;
newNode->next = NULL;
return newNode;
}
void addLast(int y)
{
struct node* hodor = createNode(y);
if(start == NULL)
{
start = hodor;
last = hodor;
}
else
{
last->next = hodor;
last = hodor;
}
}
void printLinked()
{
temp = start;
while(temp->next != NULL)
{
printf("%d\n", temp->data);
temp = temp->next;
}
printf("%d\n", temp->data);
}
void init(int size)
{
int i, number;
for( i = 0; i < size; i++ )
{
number = rand()%10000;
addLast(number);
}
}
void bubbleLinked()
{
int didSwapped, i;
struct node* temp1;
struct node* temp2 = NULL;
if(temp1 == NULL)
return;
do{
didSwapped = 0;
temp1 = start;
while(temp1->next != temp2)
{
if(temp1->data > temp1->next->data)
{
swapNode(temp1, temp1->next);
didSwapped = 1;
}
temp1 = temp1->next;
}
temp2 = temp1;
}
while(didSwapped);
}
void swapNode(struct node *x, struct node *y)
{
int temp = x->data;
x->data = y->data;
y->data = temp;
}
int main()
{
int choise;
while( 1 == 1)
{
printf("\n How many numbers do you want to create ... ");
scanf("%d", &choise);
init(choise);
bubbleLinked();
printLinked();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment