Skip to content

Instantly share code, notes, and snippets.

@lethern
Created June 8, 2019 21:47
Show Gist options
  • Select an option

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

Select an option

Save lethern/8c6f1a95ffdcf339489ee3acbba9f92a to your computer and use it in GitHub Desktop.
#include <stdio.h>
struct list_node
{
int value;
list_node* next;
list_node( int value ) : value( value ), next( NULL ) {}
};
void insert_before( list_node** head, list_node* before_this, list_node* insert_this)
{
if( *head == before_this ) {
*head = insert_this;
insert_this->next= before_this;
}
else {
list_node* after_this = *head;
while( after_this->next != before_this ) {
after_this= after_this->next;
}
insert_this->next= after_this->next;
after_this->next= insert_this;
}
}
void push( list_node* head, list_node* node )
{
while( head->next != NULL )
head = head->next;
head->next= node;
}
void test_print( list_node* head, const char* expected )
{
while( head!= NULL ){
printf( "%d ", head->value );
head= head->next;
}
printf( " (vs)\n%s\n\n", expected );
}
void test_append_to_single()
{
list_node* list = new list_node( 1 );
push( list, new list_node( 2 ) );
test_print( list, "1 2" );
}
void test_prepend_to_single()
{
list_node* list = new list_node( 1 );
insert_before( &list, list, new list_node( 2 ) );
test_print( list, "2 1" );
}
void test_prepend_to_multiple()
{
list_node* list = new list_node( 1 );
push( list, new list_node( 2 ) );
list_node* third = new list_node( 3 );
push( list, third );
insert_before( &list, third, new list_node( 0 ) );
test_print( list, "1 2 0 3" );
}
int main() {
test_append_to_single();
test_prepend_to_single();
test_prepend_to_multiple();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment