List
List is a series of nodes, the node contains two fields, a data field, a pointer field.
List memory is non-continuous, add and delete elements, the time complexity is a constant term, without moving the element array than the addition of high efficiency elements
List only allocate memory only when needed
Chain relationships require additional space saving node
#include <iostream>
#include <list>
using namespace std;
void PrintList ( list< int > mlist) {
for ( list< int > :: iterator it = mlist. begin ( ) ; it != mlist. end ( ) ; it++ ) {
cout << ( * it) << " " ;
}
cout << endl;
}
void ListTest1 ( ) {
list< int > list1 = { 1 , 45 , 4 , 55 , 78 , 12 } ;
list< int > list2 ( 5 , 6 ) ;
list< int > list3 ( list2) ;
list< int > list4 ( list1. begin ( ) , list1. end ( ) ) ;
PrintList ( list1) ;
cout << "------------------------" << endl;
PrintList ( list2) ;
cout << "------------------------" << endl;
PrintList ( list3) ;
cout << "------------------------" << endl;
PrintList ( list4) ;
}
void ListTest2 ( ) {
list< int > list1;
list1. push_back ( 12 ) ;
list1. push_back ( 45 ) ;
list1. push_front ( 1 ) ;
list1. push_front ( 52 ) ;
list1. push_back ( 1 ) ;
list1. insert ( list1. begin ( ) , 100 ) ;
list< int > :: iterator it = list1. begin ( ) ;
it++ ;
it++ ;
list1. insert ( it, 500 ) ;
list1. pop_back ( ) ;
list1. pop_front ( ) ;
list1. erase ( it, list1. end ( ) ) ;
list1. remove ( 1 ) ;
list1. clear ( ) ;
}
void ListTest ( ) {
list< int > list1 = { 1 , 45 , 4 , 55 , 78 , 12 } ;
list< int > list2;
list2. assign ( 10 , 5 ) ;
list2. swap ( list1) ;
PrintList ( list1) ;
cout << "------------------------" << endl;
PrintList ( list2) ;
}
bool MyCompare1 ( int v1, int v2) {
return v1 > v2;
}
void ListTest4 ( ) {
list< int > list1 = { 1 , 45 , 4 , 55 , 78 , 12 } ;
list1. reverse ( ) ;
PrintList ( list1) ;
list1. sort ( ) ;
PrintList ( list1) ;
list1. sort ( MyCompare1) ;
PrintList ( list1) ;
}
int main ( ) {
ListTest4 ( ) ;
return 0 ;
}