#include <iostream>
#include <string>
#include <initializer_list>
template < class T>
class LinkedList
{
private :
struct node
{
T data;
node * next;
} * head = nullptr;
public :
// Constructors and destructors
LinkedList( ) = default ;
~LinkedList( ) ;
LinkedList( const std:: initializer_list < T> & il) ;
LinkedList( std:: istream & is) ;
// Member functions
void push ( T data) ;
void reverse( ) ;
friend std:: ostream & operator << ( std:: ostream & os, const LinkedList< T> & ls) ;
} ;
template < class T>
LinkedList< T> :: ~LinkedList( )
{
node * cur = head, * next = nullptr;
while ( cur)
{
next = cur- > next;
delete cur;
cur = next;
}
}
template < class T>
LinkedList< T> :: LinkedList ( const std:: initializer_list < T> & il)
{
for ( const auto & data : il)
push ( data) ;
}
template < class T>
LinkedList< T> :: LinkedList ( std:: istream & is)
{
T temp;
while ( is >> temp)
push ( temp) ;
}
// Push to head
template < class T>
void LinkedList< T> :: push ( T data)
{
node * elem = new node;
elem- > data = data;
elem- > next = head;
head = elem;
}
template < class T>
void LinkedList< T> :: reverse ( )
{
node * prev = nullptr;
node * next = nullptr;
if ( ! head) return ;
while ( head- > next)
{
next = head- > next;
head- > next = prev;
prev = head;
head = next;
}
head- > next = prev;
}
template < class T>
std:: ostream & operator << ( std:: ostream & os, const LinkedList< T> & ls)
{
LinkedList< T> :: node * iter = ls.head ;
while ( iter)
{
os << iter- > data << " " ;
iter = iter- > next;
}
return os;
}
int main( )
{
// Integers
LinkedList< int > list{ 1 , 2 , 3 , 4 , 5 } ;
std:: cout << list << std:: endl ;
list.reverse ( ) ;
std:: cout << list << std:: endl ;
// Strings
LinkedList< std:: string > s( std:: cin ) ;
std:: cout << s << std:: endl ;
s.reverse ( ) ;
std:: cout << s << std:: endl ;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8c3RyaW5nPgojaW5jbHVkZSA8aW5pdGlhbGl6ZXJfbGlzdD4KCnRlbXBsYXRlIDxjbGFzcyBUPgpjbGFzcyBMaW5rZWRMaXN0CnsKcHJpdmF0ZToKCXN0cnVjdCB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XQgPDwgcyA8PCBzdGQ6OmVuZGw7CglzLnJldmVyc2UoKTsKCXN0ZDo6Y291dCA8PCBzIDw8IHN0ZDo6ZW5kbDsKfQ==
compilation info
prog.cpp:24:77: warning: friend declaration 'std::ostream& operator<<(std::ostream&, const LinkedList<T>&)' declares a non-template function [-Wnon-template-friend]
friend std::ostream& operator << (std::ostream &os, const LinkedList<T> &ls);
^
prog.cpp:24:77: note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here)
prog.cpp: In function 'std::ostream& operator<<(std::ostream&, const LinkedList<T>&)':
prog.cpp:83:23: error: 'iter' was not declared in this scope
LinkedList<T>::node *iter = ls.head;
^
stdout