-
-
Save tarikwaleed/db23fb4bce49a273ea47425b50cdebff to your computer and use it in GitHub Desktop.
This code shows you how to use linked list on bubble sort.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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