week 3 honours
unknown
c_cpp
4 years ago
2.3 kB
12
Indexable
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
/*
Linked-list data structure, made up of nodes
*/
struct node {
int data;
struct node* next;
struct node* previous;
};
typedef struct node node;
/*
Generates a linked-list of given size
*/
node* generate_list(int size, int range) {
node* head = malloc(sizeof(node));
node* current = head;
node* previous = NULL;
int i;
for(i = 0;i < size;i++) {
current->data = rand() % range;
if(previous != NULL) {
current->previous = previous;
}
previous = current;
if(i < (size - 1)) {
node* next = malloc(sizeof(node));
current->next = next;
current = next;
} else {
current->next = NULL;
}
}
return head;
}
/*
Prints the given list on the screen
*/
void print_list(node* head) {
int count = 0;
while(head->next != NULL) {
printf("%d\t", head->data);
head = head->next;
if(++count == 5) {
printf("\n");
count = 0;
}
}
printf("%d\n\n", head->data);
}
/*
Removes the given number from the list recursively
*/
void remove_number(node* head, int number) {
if(head->next == NULL) {
return;
}
if(head->next->data == number) {
node* duplicate = head->next;
head->next = duplicate->next;
if(head->next != NULL) {
head->next->previous = head;
}
free(duplicate);
}
if(head->next != NULL) {
if(head->next->data == number) {
remove_number(head, number);
} else {
remove_number(head->next, number);
}
}
}
/*
Removes duplicates from the given list
*/
void remove_duplicates(node* head) {
node* current = head;
while(current != NULL) {
remove_number(current, current->data);
current = current->next;
}
}
int main(void) {
srand(time(0));
int size = 200, range = 50;
node* head = generate_list(size, range);
printf("Before removing duplicates:\n");
print_list(head);
remove_duplicates(head);
printf("After removing duplicates:\n");
print_list(head);
}Editor is loading...