Skip to content

Instantly share code, notes, and snippets.

@lethern
Created June 8, 2019 22:33
Show Gist options
  • Select an option

  • Save lethern/eb7830b9ce16d856e33075d2b74a3306 to your computer and use it in GitHub Desktop.

Select an option

Save lethern/eb7830b9ce16d856e33075d2b74a3306 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct list_node
{
const char * name;
list_node* next;
};
void print( list_node* head )
{
while( head!= NULL ){
printf( "%s ", head->name );
head= head->next;
}
printf( "\n" );
}
list_node* last( list_node * head )
{
while( head->next != NULL )
head= head->next;
return head;
}
list_node * find_in_queue( list_node * head, const char* names[], int n )
{
list_node* result = NULL;
while( head != NULL ) {
for( int i=0; i < n; ++i ) {
const char* name = names[i];
if( name == NULL )continue;
if( strcmp( head->name, name ) == 0 ) {
if( result == NULL ) result = head;
names[i] = NULL;
}
}
head= head->next;
}
return result;
}
list_node* create_node( const char* name )
{
list_node* new_node = (list_node*)malloc( sizeof list_node );
new_node->name = name;
new_node->next = NULL;
return new_node;
}
list_node* add_after( list_node* after_this, const char* name )
{
list_node* new_node =create_node( name );
new_node->next = after_this->next;
after_this->next= new_node;
return new_node;
}
void add_guests_after( list_node* after_this, const char* names[], int n )
{
for( int i=0; i < n; ++i ) {
const char* name = names[i];
if( name == NULL )continue;
after_this= add_after( after_this, name );
}
}
void add_guests( list_node* queue_head, const char* names[], int n )
{
list_node* found = NULL;
found = find_in_queue( queue_head, names, n );
if( found == NULL )
found = last( queue_head );
add_guests_after( found, names, n );
}
list_node* create_ABCD()
{
list_node* queue_head = create_node( "A" );
list_node* iterator = queue_head;
iterator = add_after( iterator, "B" );
iterator = add_after( iterator, "C" );
iterator = add_after( iterator, "D" );
return queue_head;
}
void test_simple_create()
{
list_node* queue_head = create_ABCD();
print( queue_head );
}
void test_add_end()
{
list_node* queue_head = create_ABCD();
const char* guests[3] ={ "X", "Y", "Z" };
add_guests( queue_head, guests, 3 );
print( queue_head );
}
void test_add_one_middle()
{
list_node* queue_head = create_ABCD();
const char* guests[3] ={ "X", "C", "Z" };
add_guests( queue_head, guests, 3 );
print( queue_head );
}
void test_add_repeated()
{
list_node* queue_head = create_ABCD();
const char* guests[3] ={ "D", "C", "A" };
add_guests( queue_head, guests, 3 );
print( queue_head );
}
int main() {
test_simple_create();
puts( "-----" );
test_add_end();
puts( "-----" );
test_add_one_middle();
puts( "-----" );
// broken
test_add_repeated();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment