Last active
November 22, 2020 08:59
-
-
Save Roytangrb/bff641b0accc87e2a68296e20267bdfd to your computer and use it in GitHub Desktop.
Remove duplicates in a sorted list
This file contains hidden or 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
| /* | |
| * Remove duplicate from a sorted doubly linked list | |
| * By RT | |
| * 22 Nov, 2020 | |
| */ | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <time.h> | |
| typedef struct node { | |
| int val; | |
| struct node *next; | |
| struct node *prev; | |
| } node; | |
| typedef node *list; | |
| list create_list(int val) { | |
| list l = malloc(sizeof(node)); | |
| l->val = val; | |
| l->next = NULL; | |
| l->prev = NULL; | |
| return l; | |
| } | |
| list concat_list(list h1, list h2) { | |
| list head = h1; | |
| while (h1->next != NULL){ | |
| h1 = h1->next; | |
| } | |
| h1->next = h2; | |
| h2->prev = h1; | |
| return head; | |
| } | |
| void bubble_sort_list(int n, list l){ | |
| if (l == NULL) return; | |
| for (int i = n - 1; i >= 0; i --){ | |
| list head = l; | |
| for (int j = 0; j <= i; j++){ | |
| if (head->next != NULL && head->next->val < head->val){ | |
| int temp = head->val; | |
| head->val = head->next->val; | |
| head->next->val = temp; | |
| } | |
| head = head->next; | |
| } | |
| } | |
| } | |
| void dedupe(int n, list l){ | |
| while (l != NULL) { | |
| if (l->next != NULL && l->val == l->next->val){ | |
| l->next = l->next->next; | |
| } else { | |
| l = l->next; | |
| } | |
| } | |
| } | |
| void print_list(list l){ | |
| //print in row of 5 | |
| int i = 0; | |
| while (l != NULL){ | |
| printf("%-5d", l->val); | |
| if (++i % 5 == 0) printf("\n"); | |
| l = l->next; | |
| } | |
| } | |
| int main(void){ | |
| srand(time(NULL)); | |
| list l = create_list(rand() % 50); | |
| //gen random numbers and build list | |
| for (int i = 0; i < 199; i ++){ | |
| l = concat_list(create_list(rand() % 50), l); | |
| } | |
| //sort the list | |
| bubble_sort_list(200, l); | |
| print_list(l); | |
| printf("\n\n"); | |
| //remove duplicates | |
| dedupe(200, l); | |
| print_list(l); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment