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
|
#include <iostream>
#include <algorithm>
#include <memory>
struct st {
int k = 0 ;
st *next = nullptr ;
int max_value() const { // *** const
if( next == nullptr ) return k ;
else return( std::max( k, next->max_value() ) ) ;
}
void print() const {
std::cout << k << ' ' ;
if(next) next->print() ;
}
};
int main() {
// avoid dynamic memory allocation
// note: member next is default initialised to nullptr
st ar[] = { {1}, {9}, {4}, {5}, {8}, {6}, {3}, {7}, {2} } ;
const int N = sizeof(ar) / sizeof( ar[0] ) ;
for( int i = 0; i<(N-1); ++i ) ar[i].next = ar+i+1 ; // link them up, in order
// add two new items, say -5 and -2, at the back
st new_items[] { {-5}, {-2} } ;
ar[N-1].next = new_items ;
new_items[0].next = new_items + 1 ;
// add a new items, say 12 at the front
st first_item = { 12, ar } ;
// remove the two items at ar[3] and ar[4] (5 and 8) from the middle
ar[2].next = ar+5 ;
for( st* ptr = &first_item ; ptr != nullptr ; ptr = ptr->next ) {
std::cout << "sequence == [ " ;
ptr->print() ;
std::cout << "] max == " << ptr->max_value() << '\n' ;
}
}
|