Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node_tag {
char *string;
struct node_tag *next;
} node;
/* allocate and free list nodes */
/* Add NULL checks to suit */
node *newnode ( char *string ) {
node *result = malloc( sizeof(*result) );
if ( result ) {
result->string = malloc( strlen(string)+1 );
if ( result->string ) {
strcpy( result->string, string );
}
}
return result;
}
void delnode ( node *node ) {
free( node->string );
free( node );
}
/* list append */
node *append ( node *head, char *string ) {
node *new = newnode( string );
if ( head == NULL ) {
head = new;
} else {
node *temp = head;
while ( temp->next != NULL ) temp = temp->next;
temp->next = new;
}
return head;
}
/* delete duplicates from a sub-list
* return the shortened list
*/
node *del_sublist_dups ( node *head, char *match ) {
node *this = head; /* runs down the list */
node *prev = NULL; /* trails behind this by one node */
while ( this != NULL ) {
node *next = this->next; /* the next node to link to and goto */
if ( strcmp( this->string, match ) == 0 ) {
/* delete the node */
if ( prev == NULL ) {
/* the first node being a special case */
head = next;
} else {
/* otherwise make the list skip the current node */
prev->next = next;
}
delnode( this );
} else {
prev = this;
}
this = next;
}
return head;
}
/* delete dups in a list
* NB: the head element cannot change
*/
void del_dups ( node *head ) {
while ( head != NULL ) {
head->next = del_sublist_dups( head->next, head->string );
head = head->next;
}
}
void print_list ( node *list ) {
while ( list != NULL ) {
printf( "%s ", list->string );
list = list->next;
}
printf( "\n" );
}
void free_list ( node *list ) {
while ( list != NULL ) {
node *next = list->next;
delnode( list );
list = next;
}
}
int main (void) {
node *list = NULL;
list = append( list, "the" );
list = append( list, "the" ); /* example at the head of a sub-list */
list = append( list, "cat" );
list = append( list, "sat" );
list = append( list, "on" );
list = append( list, "the" ); /* example in the middle of a sub-list */
list = append( list, "mat" );
print_list( list );
del_dups( list );
print_list( list );
free_list( list );
return 0;
}