#include <iostream>
struct list // TO DO : make non-copyable, non-assignable
{
struct node
{
int value ;
node* next = nullptr ;
};
node* first = nullptr ;
};
bool empty( const list& lst ) { return lst.first == nullptr ; }
void push_back( list& lst, int value )
{
if( empty(lst) ) lst.first = new list::node{value} ;
else
{
auto p = lst.first ;
while( p->next != nullptr ) p = p->next ; // get to the last node
p->next = new list::node{value} ; // add the new item as the next of the last node
}
}
staticvoid destroy( list::node* p ) // recursively delete nodes in reverse order
{
if( p != nullptr )
{
destroy( p->next ) ;
delete p ;
}
}
// delete all nodes and make it an empty list
void clear( list& lst ) { destroy(lst.first) ; lst.first = nullptr ; }
void destroy( list& lst ) { clear(lst) ; }
void print( const list& lst )
{
std::cout << "\n[ " ;
for( auto p = lst.first ; p != nullptr ; p = p->next ) std::cout << p->value << ' ' ;
std::cout << "]\n" ;
}
int main()
{
list lst ;
int value ;
while( std::cout << "value? " && std::cin >> value ) push_back( lst, value ) ;
print(lst) ;
destroy(lst) ; // clean up once we are done
}
There is nothing complicated about it; even career teachers would be able to understand the code.
This is actually simpler (even if it may appear to be more complicated to a career teacher):
use smart pointers instead of raw pointers and resource management is automated. http://en.cppreference.com/w/cpp/memory/unique_ptr
#include <iostream>
#include <memory>
struct list
{
struct node
{
explicit node( int v ) : value(v) {}
int value ;
std::unique_ptr<node> next ;
};
std::unique_ptr<node> first ;
};
bool empty( const list& lst ) { return !lst.first ; }
void push_back( list& lst, int value )
{
if( empty(lst) ) lst.first = std::make_unique<list::node>(value) ;
else
{
auto raw_ptr = lst.first.get() ; // we use raw pointers for iteration
while( raw_ptr->next ) raw_ptr = raw_ptr->next.get() ; // get to the last node
raw_ptr->next = std::make_unique<list::node>(value) ; // append the new item at the end
}
}
void print( const list& lst )
{
std::cout << "\n[ " ;
// we use raw pointers for iteration
for( auto raw_ptr = lst.first.get() ; raw_ptr ; raw_ptr = raw_ptr->next.get() )
std::cout << raw_ptr->value << ' ' ;
std::cout << "]\n" ;
}
int main()
{
list lst ;
int value ;
while( std::cout << "value? " && std::cin >> value ) push_back( lst, value ) ;
print(lst) ;
}