Download presentation

Presentation is loading. Please wait.

Published byLesley Nicholson Modified about 1 year ago

1
Deux applications

2
Freelists Les appels système new et delete sont lents: // Singly-linked list node with freelist template class Link { private: static Link * freelist; // Début public: Elem element; // Valeur du noeud Link* next; // Pointe au nœud suivant Link(const Elem& elemval, Link* nextval =NULL) { element = elemval; next = nextval; } Link(Link* nextval =NULL) {next=nextval;} void* operator new(size_t); // Surcharge void operator delete(void*); // Surcharge };

3
Freelists (2) template Link * Link ::freelist = NULL; template // Surcharge de new void* Link ::operator new(size_t) { if (freelist == NULL) // La liste est vide return ::new Link; Link * temp = freelist; freelist = freelist->next; return temp; }

4
Freelists (3) template // Surcharge de delete void Link ::operator delete(void* ptr){ ((Link *)ptr)->next = freelist; freelist = (Link *)ptr; }

5
Tours d’Hanoi typedef int Pole; #define move(X, Y) cout << " Déplacer " << (X) << " vers " << (Y) << endl void TOH(int n, Pole start, Pole goal, Pole tmp) { if (n == 0) return; // Cas de base TOH(n-1, start, tmp, goal); // Appel récursif: n-1 disques move(start, goal); // Déplacer un disque TOH(n-1, tmp, goal, start); // Appel récursif n-1 disques }

6
enum TOHop { DOMOVE, DOTOH }; class TOHobj { public: TOHop op; int num; Pole start, goal, tmp; TOHobj(int n, Pole s, Pole g, Pole t) { op = DOTOH; num = n; start = s; goal = g; tmp = t; } TOHobj(Pole s, Pole g) { op = DOMOVE; start = s; goal = g; } };

7
void TOH(int n, Pole start, Pole goal, Pole tmp, Stack & S){ S.push(new TOHobj(n, start, goal, tmp)); // Initialisation TOHobj* t; while (S.pop(t)) { // Déterminer la prochaine tâche if (t->op == DOMOVE) // Déplacement move(t->start, t->goal); else if (t->num > 0) { // 3 étapes de la récursion en ordre inverse int num = t->num; Pole tmp = t->tmp, goal = t->goal, start = t->start; S.push(new TOHobj(num-1, tmp, goal, start)); S.push(new TOHobj(start, goal)); S.push(new TOHobj(num-1, start, tmp, goal)); } delete t; // Must delete the TOHobj we made }

Similar presentations

© 2017 SlidePlayer.com Inc.

All rights reserved.

Ads by Google