Anna Colors
You,•web development
I/O Style -
- For the input the user is required to input the number of colours and will be asked to input that many numbers.
Functions Used -
insertNode -
- It takes the linkedlist head as the pointer and takes another integer as the input, and adds it into the linkedlist.
remove duplicates -
- We iterate through the linkedlist and check whether the next block has the same color, if found we remove the duplicate.
sort
- Sorts through the linked list using bubblesort algorithm.
printinz
- We use this to print the linkedlist iterating through each element in the manner asked in the pdf.
Code -
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int color;
struct node* next;
} Linkedlist;
Linkedlist* newNode(int color) {
Linkedlist* node = (Linkedlist*) malloc(sizeof(Linkedlist));
node->color = color;
node->next = NULL;
return node;
}
void insertNode(Linkedlist** head, int color) {
Linkedlist* node = newNode(color);
if (*head == NULL) {
*head = node;
return;
}
Linkedlist* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = node;
}
void sort(Linkedlist** head) {
Linkedlist* current = *head;
Linkedlist* index = NULL;
int temp;
if (*head == NULL) {
return;
}
else {
while (current != NULL) {
index = current->next;
while (index != NULL) {
if (current->color > index->color) {
temp = current->color;
current->color = index->color;
index->color = temp;
}
index = index->next;
}
current = current->next;
}
}
}
Linkedlist* removeDuplicates(Linkedlist* head) {
Linkedlist* current = head;
while (current != NULL && current->next != NULL) {
if (current->color == current->next->color) {
Linkedlist* temp = current->next;
current->next = current->next->next;
free(temp);
}
else {
current = current->next;
}
}
return head;
}
void printinz(Linkedlist* head) {
Linkedlist* current = head;
while (current != NULL) {
if (current->next != NULL) {
printf("%d->", current->color);
}
else {
printf("%d ", current->color);
}
current = current->next;
}
printf("\n");
}
int main() {
int n;
printf("Enter the number of colors in the list: ");
scanf("%d", &n);
Linkedlist* head = NULL;
printf("Enter the colors: ");
for (int i = 0; i < n; i++) {
int color;
scanf("%d", &color);
insertNode(&head, color);
}
sort(&head);
head = removeDuplicates(head);
printf("Modified linked list: ");
printinz(head);
return 0;
}