1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
#include <iostream>
struct singly_linked_list
{
struct node
{
int value ;
node* next ;
node( int v, node* n = nullptr ) : value(v), next(n) {}
};
// ... destructor etc. ...
bool is_present( int x ) const // return true if 'x' is present in the list
{
for( node* n = first ; n != nullptr ; n = n->next ) if( n->value == x ) return true ;
return false ;
}
void push_front( int x ) // unconditionally, add 'x' to the front of the list
{
if( first == nullptr ) first = last = new node(x) ;
else
{
node* n = new node(x,first) ;
first = n ;
}
}
// if 'x' is not present in the list, add it to the front of the list
void add_unique_to_front( int x ) { if( !is_present(x) ) push_front(x) ; }
std::ostream& print( std::ostream& stm = std::cout ) const
{
for( node* n = first ; n != nullptr ; n = n->next ) stm << n->value << ' ' ;
return stm << ']' ;
}
node* first = nullptr ;
node* last = nullptr ;
};
int main()
{
singly_linked_list lst ;
for( int v : { 0, 1, 2, 1, 3, 2, 4, 5, 1, 6, 7, 5, 0, 7, 8, 8 } )
{
std::cout << "add_unique_to_front(" << v << ") => [ " ;
lst.add_unique_to_front(v) ;
lst.print() << '\n' ;
}
}
|