Anna Colors

You,web development

I/O Style -

Functions Used -

insertNode -

remove duplicates -

printinz

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;
}
© Krish Pandya.RSS