Skip to content

Commit

Permalink
Remove duplicates from sorted list
Browse files Browse the repository at this point in the history
Signed-off-by: begeekmyfriend <[email protected]>
  • Loading branch information
begeekmyfriend committed Sep 7, 2017
1 parent 16e1c77 commit 6f9ba95
Show file tree
Hide file tree
Showing 4 changed files with 105 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 082_remove_duplicates_from_sorted_list_ii/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test rm_dup.c
54 changes: 54 additions & 0 deletions 082_remove_duplicates_from_sorted_list_ii/rm_dup.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#include <stdio.h>
#include <stdlib.h>

struct ListNode {
int val;
struct ListNode *next;
};

struct ListNode* deleteDuplicates(struct ListNode* head) {
struct ListNode dummy;
struct ListNode *p, *next, *prev;
prev = &dummy;
dummy.next = head;
p = next = head;
while (p != NULL) {
while (next != NULL && next->val == p->val) {
next = next->next;
}
if (p->next == next) {
prev = p;
} else {
prev->next = next;
}
p = next;
}
return dummy.next;
}

int main(int argc, char **argv)
{
int i;
struct ListNode *head = NULL;
struct ListNode *prev = NULL;
struct ListNode *p;
for (i = 0; i < argc - 1; i++) {
p = malloc(sizeof(*p));
p->val = atoi(argv[i + 1]);
p->next = NULL;
if (head == NULL) {
head = p;
prev = head;
} else {
prev->next = p;
prev = p;
}
}
p = deleteDuplicates(head);
while (p != NULL) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
return 0;
}
2 changes: 2 additions & 0 deletions 083_remove_duplicates_from_sorted_list/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test rm_dup.c
47 changes: 47 additions & 0 deletions 083_remove_duplicates_from_sorted_list/rm_dup.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#include <stdio.h>
#include <stdlib.h>

struct ListNode {
int val;
struct ListNode *next;
};

struct ListNode* deleteDuplicates(struct ListNode* head) {
struct ListNode *p, *next;
p = next = head;
while (p != NULL) {
while (next != NULL && next->val == p->val) {
next = next->next;
}
p->next = next;
p = next;
}
return head;
}

int main(int argc, char **argv)
{
int i;
struct ListNode *head = NULL;
struct ListNode *prev = NULL;
struct ListNode *p;
for (i = 0; i < argc - 1; i++) {
p = malloc(sizeof(*p));
p->val = atoi(argv[i + 1]);
p->next = NULL;
if (head == NULL) {
head = p;
prev = head;
} else {
prev->next = p;
prev = p;
}
}
p = deleteDuplicates(head);
while (p != NULL) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
return 0;
}

0 comments on commit 6f9ba95

Please sign in to comment.