Skip to content

Instantly share code, notes, and snippets.

@kkabdol
Last active October 19, 2019 12:33
Show Gist options
  • Save kkabdol/c5178255f21a9ee69cee127eef4ee839 to your computer and use it in GitHub Desktop.
Save kkabdol/c5178255f21a9ee69cee127eef4ee839 to your computer and use it in GitHub Desktop.
Reverse Linked List (Review the last test)
// https://www.geeksforgeeks.org/reverse-a-linked-list/
#include <iostream>
#include <cassert>
using namespace std;
struct List
{
List* next;
int data;
};
List* reverse( List* list )
{
List *current = list;
List *prev = nullptr;
while( current != nullptr )
{
List* tmp = current->next;
current->next = prev;
prev = current;
current = tmp;
}
return prev;
}
List* create( int data );
void append( List* list, List* add );
void init( List** list );
void deinit( List** list );
void append( List* list, List* add );
void print( List* list );
int main()
{
List* list = nullptr;
init( &list );
list = reverse( list );
print( list );
deinit( &list );
return 0;
}
List* create( int data )
{
List* list = new List;
list->next = nullptr;
list->data = data;
return list;
}
void init( List** list )
{
assert( *list == nullptr );
*list = create( 0 );
for( int i = 1; i < 10; ++i )
{
List* l = create( i );
append( *list, l );
}
}
void deinit( List** list )
{
while( *list != nullptr )
{
List* next = ( *list )->next;
delete ( *list );
*list = next;
}
*list = nullptr;
}
void append( List* list, List* add )
{
assert( list != nullptr );
assert( add != nullptr );
while( list->next != nullptr )
{
list = list->next;
}
list->next = add;
}
void print( List* list )
{
assert( list != nullptr );
cout << "print list: " << endl;
while( list != nullptr )
{
cout << list->data << " ";
list = list->next;
}
cout << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment