Sei sulla pagina 1di 169

46 Eser

izi di C++

V0.8

Mar ello Esposito

Copyright

2006

Mar ello Esposito. Permission is granted to opy, distri-

bute and/or modify this do ument under the terms of the GNU Free Do umentation Li ense, Version 1.2 or any later version published by the Free
Software Foundation; with no Invariant Se tions, no Front-Cover Texts, and
no Ba k-Cover Texts. A opy of the li ense is in luded in the se tion entitled
"GNU Free Do umentation Li ense".

Indi e
Prefazione

I Eser izi

11

EL Eser izi su liste

12

EL.1

Lista Sempli emente Collegata

. . . . . . . . . . . . . . . .

12

EL.2

Somma Elementi . . . . . . . . . . . . . . . . . . . . . . . .

13

EL.3

Coda Pari . . . . . . . . . . . . . . . . . . . . . . . . . . . .

13

EL.4

Min e Max

. . . . . . . . . . . . . . . . . . . . . . . . . . .

13

EL.5

ListaStati a . . . . . . . . . . . . . . . . . . . . . . . . . . .

14

EL.6

Ordinata . . . . . . . . . . . . . . . . . . . . . . . . . . .

14

EL.7

Elimina Tutti . . . . . . . . . . . . . . . . . . . . . . . . . .

15

EL.8

Somma Coda . . . . . . . . . . . . . . . . . . . . . . . . . .

15

EL.9

Sposta Testa in Coda

. . . . . . . . . . . . . . . . . . . . .

15

EL.10

Elimina Pari e Dispari . . . . . . . . . . . . . . . . . . . . .

15

EL.11

Lista Doppiamente Collegata . . . . . . . . . . . . . . . . .

16

EL.12

Ribalta

17

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

EA Eser izi su alberi binari

18

EA.1

Albero Binario . . . . . . . . . . . . . . . . . . . . . . . . .

18

EA.2

Numero Elementi

. . . . . . . . . . . . . . . . . . . . . . .

19

EA.3

O orrenze

. . . . . . . . . . . . . . . . . . . . . . . . . . .

19

EA.4

O orrenza Massima . . . . . . . . . . . . . . . . . . . . . .

19

EA.5

Profondit Limitata

20

. . . . . . . . . . . . . . . . . . . . . .

EA.6

Somma

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

21

EA.7

Sostituis i . . . . . . . . . . . . . . . . . . . . . . . . . . . .

21

EA.8

Conta Min e Max

. . . . . . . . . . . . . . . . . . . . . . .

21

EA.9

Profondit Maggiore di Due . . . . . . . . . . . . . . . . . .

22

EA.10

Profondita Maggiore Di . . . . . . . . . . . . . . . . . . . .

22

EA.11

Profondit Massima

22

. . . . . . . . . . . . . . . . . . . . . .

INDICE
EA.12

Somma Livello . . . . . . . . . . . . . . . . . . . . . . . . .

23

EA.13

Eliminazione Foglia

. . . . . . . . . . . . . . . . . . . . . .

23

EA.14

Eliminazione Foglie

. . . . . . . . . . . . . . . . . . . . . .

23

EA.15

Operatore di Confronto

EA.16

Conta Nodi non Foglia . . . . . . . . . . . . . . . . . . . . .

24

EA.17

Conta Nodi . . . . . . . . . . . . . . . . . . . . . . . . . . .

24

. . . . . . . . . . . . . . . . . . . .

EP Eser izi su pile


EP.1

24

25

Push Greater . . . . . . . . . . . . . . . . . . . . . . . . . .

EC Eser izi su ode

25

27

EC.1

Coda

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

27

EC.2

Coda on Perdite . . . . . . . . . . . . . . . . . . . . . . . .

28

EC.3

Coda a Priorit . . . . . . . . . . . . . . . . . . . . . . . . .

29

EC.4

PopMinMax

30

. . . . . . . . . . . . . . . . . . . . . . . . . .

EX Altri eser izi

32

EX.1

A umulatore . . . . . . . . . . . . . . . . . . . . . . . . . .

32

EX.2

Cifratore

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

32

EX.3

Lista Della Spesa . . . . . . . . . . . . . . . . . . . . . . . .

33

EX.4

Predittore di Temperatura

. . . . . . . . . . . . . . . . . .

34

EX.5

Contenitore . . . . . . . . . . . . . . . . . . . . . . . . . . .

35

EX.6

Lista Prenotazioni . . . . . . . . . . . . . . . . . . . . . . .

37

EX.7

Classi a

38

EX.8

Agenzia Matrimoniale . . . . . . . . . . . . . . . . . . . . .

39

EX.9

Par o Pattini . . . . . . . . . . . . . . . . . . . . . . . . . .

41

EX.10

Timer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

42

EX.11

Timer Avanzato

. . . . . . . . . . . . . . . . . . . . . . . .

44

EX.12

Votazioni . . . . . . . . . . . . . . . . . . . . . . . . . . . .

44

. . . . . . . . . . . . . . . . . . . . . . . . . . . .

II Soluzioni

46

SL Soluzioni degli eser izi su liste

47

SL.1

Lista Sempli emente Collegata

. . . . . . . . . . . . . . . .

47

SL.2

Somma Elementi . . . . . . . . . . . . . . . . . . . . . . . .

52

SL.3

Coda Pari . . . . . . . . . . . . . . . . . . . . . . . . . . . .

53

SL.4

Min e Max

. . . . . . . . . . . . . . . . . . . . . . . . . . .

56

SL.5

ListaStati a . . . . . . . . . . . . . . . . . . . . . . . . . . .

56

SL.6

Ordinata . . . . . . . . . . . . . . . . . . . . . . . . . . .

58

SL.7

Elimina Tutti . . . . . . . . . . . . . . . . . . . . . . . . . .

59

INDICE

SL.8

Somma Coda . . . . . . . . . . . . . . . . . . . . . . . . . .

59

SL.9

Sposta Testa in Coda

. . . . . . . . . . . . . . . . . . . . .

60

SL.10

Elimina Pari e Dispari . . . . . . . . . . . . . . . . . . . . .

61

SL.11

Lista Doppiamente Collegata . . . . . . . . . . . . . . . . .

62

SL.12

Ribalta

65

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

SA Soluzioni degli eser izi su alberi binari

69

SA.1

Albero Binario . . . . . . . . . . . . . . . . . . . . . . . . .

69

SA.2

Numero Elementi

. . . . . . . . . . . . . . . . . . . . . . .

75

SA.3

O orrenze

. . . . . . . . . . . . . . . . . . . . . . . . . . .

75

SA.4

O orrenza Massima . . . . . . . . . . . . . . . . . . . . . .

76

SA.5

Profondit Limitata

80

. . . . . . . . . . . . . . . . . . . . . .

SA.6

Somma

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

81

SA.7

Sostituis i . . . . . . . . . . . . . . . . . . . . . . . . . . . .

81

SA.8

Conta Min e Max

. . . . . . . . . . . . . . . . . . . . . . .

82

SA.9

Profondit Maggiore di Due . . . . . . . . . . . . . . . . . .

87

SA.10

Profondita Maggiore Di . . . . . . . . . . . . . . . . . . . .

88

SA.11

Profondit Massima

. . . . . . . . . . . . . . . . . . . . . .

88

SA.12

Somma Livello . . . . . . . . . . . . . . . . . . . . . . . . .

89

SA.13

Eliminazione Foglia

. . . . . . . . . . . . . . . . . . . . . .

89

. . . . . . . . . . . . . . . . . . . . . .

94

SA.14

Eliminazione Foglie

SA.15

Operatore di Confronto

SA.16

Conta Nodi non Foglia . . . . . . . . . . . . . . . . . . . . . 100

SA.17

Conta Nodi . . . . . . . . . . . . . . . . . . . . . . . . . . . 101

. . . . . . . . . . . . . . . . . . . . 100

SP Soluzioni degli eser izi su pile


SP.1

107

Push Greater . . . . . . . . . . . . . . . . . . . . . . . . . . 107

SC Soluzioni degli eser izi su ode

111

SC.1

Coda

SC.2

Coda on Perdite . . . . . . . . . . . . . . . . . . . . . . . . 115

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111

SC.3

Coda a Priorit . . . . . . . . . . . . . . . . . . . . . . . . . 119

SC.4

PopMinMax

. . . . . . . . . . . . . . . . . . . . . . . . . . 124

SX Soluzioni degli altri eser izi

125

SX.1

A umulatore . . . . . . . . . . . . . . . . . . . . . . . . . . 125

SX.2

Cifratore

SX.3

Lista Della Spesa . . . . . . . . . . . . . . . . . . . . . . . . 127

. . . . . . . . . . . . . . . . . . . . . . . . . . . . 126

SX.4

Predittore di Temperatura

SX.5

Contenitore . . . . . . . . . . . . . . . . . . . . . . . . . . . 133

. . . . . . . . . . . . . . . . . . 131

SX.6

Lista Prenotazioni . . . . . . . . . . . . . . . . . . . . . . . 136

INDICE

SX.7

Classi a

. . . . . . . . . . . . . . . . . . . . . . . . . . . . 140

SX.8

Agenzia Matrimoniale . . . . . . . . . . . . . . . . . . . . . 144

SX.9

Par o Pattini . . . . . . . . . . . . . . . . . . . . . . . . . . 148

SX.10

Timer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154

SX.11

Timer Avanzato

SX.12

Votazioni . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157

. . . . . . . . . . . . . . . . . . . . . . . . 155

GNU Free Do umentation Li ense


A.1

Appli ability and Denitions

A.2

Verbatim Copying

161

. . . . . . . . . . . . . . . . . 161

. . . . . . . . . . . . . . . . . . . . . . . 163

A.3

Copying in Quantity . . . . . . . . . . . . . . . . . . . . . . 163

A.4

Modi ations . . . . . . . . . . . . . . . . . . . . . . . . . . 164

A.5

Combining Do uments . . . . . . . . . . . . . . . . . . . . . 165

A.6

Colle tion of Do uments . . . . . . . . . . . . . . . . . . . . 166

A.7

Aggregation with Independent Works

A.8

Translation . . . . . . . . . . . . . . . . . . . . . . . . . . . 166

A.9

Termination

A.10

Future revisions of this li ense

. . . . . . . . . . . . 166

. . . . . . . . . . . . . . . . . . . . . . . . . . 166
. . . . . . . . . . . . . . . . 167

Prefazione
Gli eser izi presentati in questo eser iziario sono stati proposti a studenti di
Ingegneria delle Tele omuni azioni nell'ambito di un orso di Programmazio-

ne I.
Il orso aveva lo s opo di introdurre alla programmazione orientata agli
oggetti (OOP) utilizzando il linguaggio C++. Una rilevante parte del programma arontava lo studio dei tipi di dati astratti, on parti olare enfasi alle
strutture dati di tipo ontenitore, stressandone i on etti di in apsulamento
ed interfa ia.

Gli eser izi dedi ati all'approfondimento di questi on etti

sono stati ra olti in questo eser iziario, insieme on le relative soluzioni.

A hi rivolto questo testo


Gli studenti he appro iano allo studio del linguaggio, in o asione di orsi
di studi superiori, troveranno utile studiare e risolvere gli eser izi ontenuti
in questo testo.

Se da un lato questi favoris ono l'a quisizione delle ri or-

renti te ni he legate alla realizzazione ed all'uso di ontenitori, dall'altro


rappresentano un pretesto per mettere in prati a appro i algoritmi i alla
risoluzione di problemi pi generi i.
Non essendo questo un libro di teoria, lo studio di uno dei numerosi testi
dedi ati alle nozioni della programmazione, alle regole ed alla sintassi del
linguaggio C++, risulta propedeuti o. Il testo ertamente pi rappresentativo s ritto dall'inventore del linguaggio, Bjarne Stroustrup [1. Esistono
omunque numerosi altri testi orientati all'apprendimento del linguaggio, tra
ui [2, 3.

La struttura degli eser izi


Questo eser iziario ontiene dierenti tipologie di eser izi: al uni ri hiedono
la realizzazione di un'intera struttura dati di tipo ontenitore, mediante il
ostrutto

lass

del linguaggio, fornendo allo studente la spe i a in forma

Prefazione

di interfa ia dei lassi i metodi di ui tali strutture sono dotate (aggiunta di


un elemento, onteggio degli elementi, svuotamento, visita, et .). Altri eser izi, basandosi sulle suddette implementazioni, ri hiedono la realizzazione di
funzionalit nalizzate ad eettuare parti olari elaborazioni sugli elementi
ontenuti (per esempio inserimenti o eliminazioni ondizionate, somme, spostamenti, et .). Inne, al uni eser izi ri hiedono la realizzazione di strutture
dedi ate a risolvere parti olari problemi, e quindi prive dei lassi i requisiti
di generalit.
Per ogni metodo da implementare, la tra ia fornis e le seguenti informazioni:

il nome del metodo;

l'insieme dei parametri di ingresso;

l'insieme dei parametri di us ita;

la des rizione della funzionalit he il metodo deve realizzare.

Per esempio, la spe i a di un ipoteti o metodo di eliminazione di elementi da una lista, potrebbe apparire ome segue.

Nome

Elimina()

Param. Ingr.
TElem

Param. Us .

unsigned int

Elimina dalla struttura tutte le o orrenze dell'elemento spe i ato dal


parametro di ingresso. Restituis e il numero delle eliminazioni eettuate.
Nel aso in ui un insieme di parametri fosse vuoto, si utilizzer il simbolo

Talvolta pu a adere he nella des rizione del funzionamento del meto-

do non si prenda in onsiderazione la totalit dei asi he possono veri arsi


(pre- ondizioni), limitandosi a des riverne il omportamento nei asi d'uso
pi omuni. In questo aso, il programmatore pu s egliere arbitrariamente
un omportamento per tutti i asi non espli itamente onsiderati.
Per quanto riguarda le strategie di gestione della memoria, la realizzazione
delle strutture dati pu basarsi su un appro io di tipo stati o (uso di vettori
allo ati sullo sta k) oppure dinami o (realizzazione di strutture on atenate
on puntatori ed allo ate nell'heap mediante ostrutto

new).

Questa s elta,

in al uni asi, las iata alla sensibilit dello studente.


Al une delle soluzioni presentate onstano di un uni o le avente estensione

. pp.

In altri asi stato presentato un appro io pi modulare, mediante

separazione del odi e su pi les (aventi estensioni

.h e . pp),

enfatizzando

Prefazione

in misura an ora maggiore i diversi moduli di ui l'astrazione di volta in


volta ostituita.
Per ognuno degli eser izi, oltre alla tra ia, si fornis e la soluzione onsistente nell'implementazione dei metodi onformi all'interfa ia spe i ata
dalla tra ia. Nel aso in ui la tra ia ri hieda di realizzare un'intera struttura dati (e non solo dei metodi basati su di essa), nella soluzione viene an he
fornito un modulo di test (di solito rappresentato dalla funzione

main()) utile

es lusivamente al ollaudo delle funzionalit della lasse.


Al ne di preservare una maggiore generalit delle strutture dati realizzate, un espli ito requisito omune a tutti gli eser izi onsiste nel vietare l'uso
dei me anismi di (I/O) nell'implementazione dei metodi della lasse. La responsabilit di prelevare i dati da tastiera e mostrare i risultati sulla onsole
viene pertanto delegata al modulo di test. Un'uni a deroga a questa regola
relativa al metodo di visita delle strutture (di solito ontrassegnato dal nome

Stampa()):

il on etto di iteratore, utile ad astrarre l'attraversamento di una

struttura ontenitore, non di solito noto agli studenti di un orso di base.


Il lettore interessato pu fare riferimento alla Standard Template Library
(STL) [4, peraltro di notevole utilit in reali ontesti di sviluppo software.
Per le operazioni di I/O si utilizzano le funzionalit messe a disposizione dalla
libreria standard

iostream,

ed in parti olare dai suoi oggetti

in

out.

Spesso nelle tra e non ri hiesta l'implementazione di un ostruttore di


opia oppure di un operatore di assegnazione.

Questi due metodi, se non

deniti in una lasse, vengono automati amente sintetizzati dal ompilatore e, se invo ati dall'utente, produ ono una opia super iale dell'oggetto
(shallow- opy ). Se questo omportamento s orretto  o omunque indesiderato  possibile rendere del tutto indisponibili le funzionalit di opia o
assegnazione tra oggetti della lasse. Ci si ottiene di hiarando nella sezione

private

della lasse i due metodi in questione e non fornendone al una im-

plementazione [5. Cos fa endo, qualsiasi ostrutto he nis a per invo are
uno di questi due metodi produrr un errore di ompilazione. Tale te ni a
viene spesso utilizzata nelle soluzioni degli eser izi presentati.

Compilare i sorgenti
Tutti i sorgenti presentati sono stati ompilati on la versione 3.3.1 della suite di ompilazione GNU/GCC [6, utilizzando le seguenti opzioni di
ompilazione:

-Wall ansi pedanti

Prefazione
L'opzione

-Wall

ri hiede al ompilatore di non inibire la maggior parte

dei messaggi di warning he, pur non ompromettendo la orretta ompilazione del programma, sono sintomi di impre isioni all'interno del odi e. Le
altre due opzioni indu ono il ompilatore ad a ettare es lusivamente odi e
strettamente aderente allo standard ISO-C++ [7, riutando la ompilazione
di eventuali estensioni non standard del linguaggio.
Il odi e sorgente delle soluzioni stato s ritto utilizzando l'ambiente
di sviluppo Dev-C++ [8, nella sua versione 4.9.9.0, utilizzabile su sistemi
TM
operativi della famiglia Mi rosoft
Windows. Tale software onsiste di un
editor gra o he funge da interfa ia per le operazioni di stesura, ompilazione e debugging del odi e sorgente, oltre a fornire ed installare an he la
suite di ompilazione GNU/GCC. In ogni aso, pur h disponga di un ompilatore onforme allo standard ISO-C++, qualsiasi altro ambiente di sviluppo,
o an he un sempli e editor di testi, possono essere onsiderati validi ai ni
della stesura del odi e sorgente.

Uno sguardo al futuro


Quelli he alla ne di questo eser iziario penseranno: S, e allora? , probabilmente sono pronti per arontare uno studio pi approfondito della programmazione, he non si esauris e on il possesso delle nozioni su un linguaggio. Tra un individuo he onos a un linguaggio di programmazione ed un
esperto di programmazione ' un dierenza analoga a quella he esiste tra
un individuo he sappia s rivere ed uno s rittore. Un buon programmatore
non quello he sa arontare la omplessit, ma quello he sa dominarla.
Certamente la onos enza della sintassi del linguaggio un primo passo indispensabile, ma hi vuole approfondire questo per orso non pu fare a meno
di a quisire le nozioni della progettazione, le buone prassi per la stesura del
odi e e gli strumenti forniti dalle numerose librerie standard oggi disponibili. solo attraverso questa strada he diviene possibile s rivere appli azioni
non banali, preservandone le aratteristi he di omprensibilit, estensibilit,
manutenibilit, orrettezza e, in una sola parola, di qualit. Programmare
utilizzando l'ereditariet, il polimorsmo, i me anismi delle e ezioni, delle
asserzioni, dei templates, le numerose librerie pi o meno standard, signi a
disporre di strumenti semanti amente molto potenti, oltre he ben onsolidati; signi a delegare al ompilatore lo svolgimento di una serie di operazioni
e di ontrolli he, in alternativa, peserebbero sulle spalle del programmatore,
oppure non verrebbero messi in essere aatto.

Si pensi ad esempio al seguente sempli e problema: si vuole realizzare un programma


C++ he, data una stringa di testo omunque lunga, al oli l'o orrenza delle parole

Prefazione

ontenute in essa. Utilizzando es lusivamente i ostrutti messi a disposizione dal linguaggio


sarebbe ne essario pro edere se ondo i seguenti passi:
1. progettazione di una struttura dati apa e di ontenere sequenze di aratteri omunque lunghe;
2. progettazione di una struttura ad a esso tabellare apa e di ontenere oppie del
tipo (stringa, intero);
3. progettazione di un algoritmo he analizzi la stringa, la suddivida nelle singole
parole omponenti e popoli oerentemente la struttura tabellare.
Utilizzando inve e quanto messo a disposizione dalla libreria STL [4, il programma
suddetto apparirebbe ome segue:

int

main ( ) {
s t r i n g buf ;
map<s t r i n g , int > m;
while ( i n >> buf )
m[ buf ++;

Una volta he la STL sia nota, i vantaggi di un tale appro io risultano evidenti relativamente agli aspetti di (i) tempo di stesura; (ii) orrettezza del odi e; (iii) individuazione
degli errori; (iv) omprensibilit; (v) manutenibilit; (vi) estensibilit; (vii) aderenza agli
standard.
Nell'apprendere le nozioni della progettazione e le buone prassi per la
stesura del odi e, as oltare osa hanno da dir i `i giganti' al proposito, pu
servire molto.

A questo s opo non si pu fare a meno di itare dei testi

disponibili in letteratura, universalmente onsiderati dei lassi i.

Design Patterns [9 probabilmente il pi bel testo mai s ritto nell'ambito


della progettazione software, onsiderando an he le profonde riper ussioni
he esso ha poi avuto sul on etto di buona progettazione software orientata
agli oggetti, tanto da essere an ora oggi il libro di gran lunga pi itato
nel suo genere. In questo testo gli autori introdu ono il on etto di pattern

progettuale software (design pattern ); ad un livello di astrazione superiore a


quello di qualsiasi linguaggio di programmazione, presentano poi 55 soluzioni
a problemi omuni nell'ambito della progettazione, on esempi in linguaggio
C++. Imperdibile.
In programmazione un problema pu essere spesso risolto seguendo un notevole numero di dierenti strade, ognuna delle quali assoggetta il programmatore ad a ettare determinati ompromessi. I due libri Ee tive C++ [5
e More Ee tive C++ [10 ontengono una ollezione di linee guida utili a
omprendere osa fare  e osa non fare  on il linguaggio C++. Una nutrita s hiera di programmatori ha assimilato da questi due testi un orretto
stile di programmazione, ed ha imparato ad evitare i ri orrenti trabo hetti

Prefazione

10

in agguato durante le fasi di stesura di odi e in linguaggio C++. Il su esso


di questi testi tale he oggi il ompilatore GNU/GCC dotato di un'opzione di ompilazione he produ e dei warnings in aso di violazione delle linee

guida ontenute in Ee tive C++ .


Chi voglia realmente approfondire la propria onos enza del C++, non
pu fare a meno di assimilare le te ni he di programmazione basate sul me anismo dei template e della programmazione generi a (generi programming).

Modern C++ Design [11 parti olarmente illuminante sotto questo punto di
vista. Il libro apre le porte ad un utilizzo estremamente elegante dei template,
inimmaginato perno da hi li aveva originariamente progettati. Seguendo la
sua impostazione nella stesura del software e le sue linee guida si perviene al
progetto di ar hitetture software limpide e snelle, ma ontemporaneamente
estremamente potenti e versatili.

Contattare l'autore
Commenti, suggerimenti e segnalazioni sono graditi.
ontattato all'indirizzo email:

1 L'opzione

: -Weff ++.

mespositunina.it

L'autore pu essere

Parte I
Eser izi

11

Capitolo EL
Eser izi su liste
EL.1 Lista Sempli emente Collegata
Soluzione a pag. 47

Si realizzi la struttura dati


uguale al tipo

int

Lista.

Il tipo

TElem

degli elementi ontenuti sia

del linguaggio. La lista sia dotata dei metodi riportati di

seguito.
Nome

Param. Ingr.

Param. Us .

Lista()

Lista

TElem

int

Costruttore senza parametri.

Lista()
Costruttore di opia.

Lista()
Distruttore.

Inseris i()
Inserimento in testa alla lista.

NumeroElementi()

Restituis e il numero degli elementi ontenuti nella lista.

Svuota()

TElem

Svuota la lista.

Elimina()

Elimina un elemento dalla lista, se presente.

12

EL. Eser izi su liste


Stampa()

13

Stampa sullo standard output tutti gli elementi ontenuti nella lista.

Ri er a()

TElem

bool

Predi ato indi ante la presenta di un elemento.

EL.2 Somma Elementi


Soluzione a pag. 52

Dotare la lasse

Lista (vedi EL.1) del metodo Somma() se ondo la seguente

spe i a.
Nome

Param. Ingr.

Param. Us .

Somma()

TElem

Restituis e la somma degli elementi presenti nella lista.

EL.3 Coda Pari


Soluzione a pag. 53

Dotare la lasse

LinkedList

(vedi EL.1) del metodo

CodaPari(),

se ondo

la seguente interfa ia.


Nome

Param. Ingr.

CodaPari()
true

Restituis e

Param. Us .

se l'elemento in oda pari,

false

bool
altrimenti.

EL.4 Min e Max


Soluzione a pag. 56

Dotare la lasse

Lista (vedi EL.1) del metodo MinMax() se ondo la seguente

spe i a.
Nome

Param. Ingr.

Param. Us .

MinMax()

TElem,TElem

Restituis e gli elementi minimo e massimo all'interno della lista. In


aso di lista vuota l'us ita di questo metodo non spe i ata.

EL. Eser izi su liste

14

EL.5 ListaStati a
Soluzione a pag. 56

Si realizzi la struttura dati


memoria di tipo stati o. Il
tipo

int

Lista se ondo un appro io all'allo azione della


tipo TElem degli elementi ontenuti sia uguale al

del linguaggio. La lista sia dotata dei metodi riportati di seguito.

Nome

Param. Ingr.

Param. Us .

Lista()

TElem

Costruttore.

Lista()
Distruttore.

Inseris iInCoda()

Inseris e un elemento in oda alla lista.

Svuota()

Count()

L'uni o metodo della lasse Lista he pu utilizzare lo standard-output


( out) il metodo

Stampa().

Gli altri metodi (pubbli i, privati o protetti)

non possono fare uso delle funzionalit di stampa.

EL.6 Ordinata
Soluzione a pag. 58

Dotare la lasse

Lista

(vedi EL.5) del metodo

EOrdinata(),

se ondo la

seguente interfa ia.


Nome

Param. Ingr.

Param. Us .

EOrdinata()
Restituis e true

bool

se la lista ordinata se ondo la relazione di

ordinamento res ente per gli interi,

false

altrimenti.

EL. Eser izi su liste

15

EL.7 Elimina Tutti


Soluzione a pag. 59

Dotare la lasse

Lista (vedi EL.5) del metodo EliminaTutti(),

se ondo la

seguente interfa ia.


Nome

Param. Ingr.

Param. Us .

EliminaTutti()

TElem

int

Elimina tutte le o orrenze dell'elemento spe i ato presenti nella


lista. Restituis e il numero di o orrenze eliminate.

EL.8 Somma Coda


Soluzione a pag. 59

Dotare la lasse

LinkedList

(vedi EL.1) del metodo

SommaCoda(),

se ondo

la seguente interfa ia.


Nome

Param. Ingr.

Param. Us .

SommaCoda()

Somma a tutti gli elementi della lista il valore dell'elemento di oda.

EL.9 Sposta Testa in Coda


Soluzione a pag. 60

Dotare la lasse

LinkedList (vedi EL.1) del metodo SpostaTestaInCoda(),

se ondo la seguente interfa ia.


Nome

Param. Ingr.

Param. Us .

SpostaTestaInCoda()

bool

Sposta in oda alla lista l'elemento di testa.

true

se lo spostamento eettuato,

false

Il metodo restituis e

altrimenti.

EL.10 Elimina Pari e Dispari


Soluzione a pag. 61

LinkedList (vedi EL.1) dei metodi EliminaElPostoPari()


EliminaElPostoDispari(), se ondo la seguente interfa ia.

Dotare la lasse
ed

EL. Eser izi su liste

16

el

el

el
last

first

Figura EL.1: Struttura della lista doppiamente ollegata

Nome

Param. Ingr.

Param. Us .

EliminaElPostoPari()

unsigned int

Elimina dalla lista tutti gli elementi di posto pari (0, 2, 4, ...).
Restituis e il numero di elementi eliminati.

EliminaElPostoDispari()

unsigned int

Elimina dalla lista tutti gli elementi di posto dispari (1, 3, 5, ...).
Restituis e il numero di elementi eliminati.

EL.11 Lista Doppiamente Collegata


Soluzione a pag. 62

Si realizzi in linguaggio C++ il tipo di dato astratto


ostrutto

lass del linguaggio.

Lista mediante uso del

L'implementazione deve essere realizzata me-

diante puntatori ed allo azione dinami a della memoria se ondo l'appro io


di lista doppiamente ollegata. Ogni elemento, io, punta ontemporaneamente al pre edente ed al su essivo (vedi Figura EL.1). Gli elementi della
lista siano di tipo

TElem

uguale al tipo

int.

Di seguito riportata la spe i a dei metodi pubbli i da implementare


per la lasse

Lista.

Nome

Param. Ingr.

Param. Us .

Lista()

TElem

Costruttore.

Lista()
Distruttore.

Inseris i()

Inseris e un elemento in oda alla lista.

Svuota()
Svuota la lista.

EL. Eser izi su liste

17

Count()

unsigned int

Conta gli elementi ontenuti nella lista.

StampaDiretta()

Stampa il ontenuto della lista sullo standard output, dall'elemento


di testa all'elemento di oda.

StampaInversa()

Stampa il ontenuto della lista sullo standard output, dall'elemento


di oda all'elemento di testa.

StampaAlternata()

Stampa il ontenuto della lista nel seguente ordine: primo elemento, ultimo elemento, se ondo elemento, penultimo elemento, terzo
elemento, terzultimo elemento...
Gli uni i metodi della lasse Lista he possono utilizzare lo standardoutput ( out) sono i metodi di stampa. Gli altri metodi (pubbli i, privati o
protetti) non possono fare uso degli oggetti per l'I/O.
Si realizzi una funzione

main() he permetta di eettuare il ollaudo della

struttura dati realizzata.

EL.12 Ribalta
Soluzione a pag. 65

Dotare la lasse

Lista

(vedi EL.1) del metodo

Ribalta()

se ondo la se-

guente spe i a.
Nome

Param. Ingr.

Param. Us .

Ribalta()

Ribalta la posizione di tutti gli elementi della lista. Alla hiamata di


tale metodo il primo elemento diventa l'ultimo, il se ondo diventa il
penultimo. . . l'ultimo diventa il primo.

Capitolo EA
Eser izi su alberi binari
EA.1 Albero Binario
Soluzione a pag. 69

Realizzare la lasse
tipo

int.

AlberoBinario.

Il tipo

TElem

dei suoi elementi sia il

L'implementazione di tutti i metodi sia basata su appositi metodi

ri orsivi. L'interfa ia della lasse sia la seguente.


Nome

Param. Ingr.

Param. Us .

AlberoBinario()

Costruttore della struttura.

AlberoBinario()

AlberoBinario

Costruttore di opia.

AlberoBinario()
Distruttore della struttura.

AggiungiElem()

TElem

Metodo di aggiunta di un elemento all'albero.

InAlb()

TElem

Ri er a un elemento nell'albero.

Restituis e

l'elemento spe i ato sia presente nell'albero,

Elimina()

TElem

true
false

bool
nel aso in ui
altrimenti.

Elimina l'elemento spe i ato dall'albero.

Svuota()

Svuota la struttura.
18

EA. Eser izi su alberi binari


PreOrdine()

19

Eettua una visita in pre-ordine dell'albero, stampando tutti gli


elementi sullo standard output.

PostOrdine()

Eettua una visita in post-ordine dell'albero, stampando tutti gli


elementi sullo standard output.

InOrdine()

Eettua una visita in ordine dell'albero, stampando tutti gli elementi


sullo standard output.

EA.2 Numero Elementi


Soluzione a pag. 75

Dotare la lasse

AlberoBinario (vedi EA.1) del metodo NumElem() se ondo

la seguente spe i a.
Nome

Param. Ingr.

Param. Us .

NumElem()

unsigned int

Restituis e il numero degli elementi presenti nell'albero.

EA.3 O orrenze
Soluzione a pag. 75

Dotare la lasse

AlberoBinario

(vedi EA.1) del metodo

O orrenze(),

se ondo la seguente interfa ia.


Nome

Param. Ingr.

Param. Us .

O orrenze()

TElem

unsigned int

Restituis e le o orrenze dell'elemento spe i ato nell'albero.

EA.4 O orrenza Massima


Soluzione a pag. 76

Modi are la lasse

AlberoBinario

(vedi EA.1) per prevedere un'o orren-

za massima degli elementi in esso inseriti. Pi pre isamente, il ostruttore


deve a ettare ome parametro di ingresso un numero intero positivo (per es.

EA. Eser izi su alberi binari


maxo );

20

l'inserimento di un nuovo elemento nell'albero deve andare a buon

ne solo se tale elemento presente on o orrenza minore di

maxo .

Di seguito riportata la spe i a dei due metodi pubbli i da implementare


per la lasse

AlberoBinario.

Nome

Param. Ingr.

Param. Us .

AlberoBinario()

unsigned int

Costruttore on parametro di ingresso di tipo intero non negativo. Il


parametro di ingresso rappresenta l'o orrenza massima on ui gli
elementi potranno essere presenti nell'albero.

Inseris i()
Inseris e
on

TElem

l'elemento

o orrenza

spe i ato

minore

bool

nell'albero

dell'o orrenza

se

esso

massima

presente

spe i ata

nel

ostruttore.
Il metodo restituis e

true

false

a se onda he l'inserimento si

avvenuto o meno.

EA.5 Profondit Limitata


Soluzione a pag. 80

Modi are la lasse

AlberoBinario

(vedi EA.1) per prevedere il non su-

peramento di una profondit massima spe i ata all'atto della ostruzione


della struttura.
Di seguito riportata la spe i a dei due nuovi metodi pubbli i da implementare per la lasse

AlberoBinario:

Nome

Param. Ingr.

Param. Us .

AlberoBinario()

unsigned int

Costruttore on parametro intero non negativo. Il parametro di ingresso indi a la massima profondit he l'albero pu assumere durante
il suo i lo di vita.

Inseris i()

TElem

bool

Inseris e in maniera ordinata l'elemento spe i ato nell'albero solo se


esso non supera la massima profondit prevista per l'albero. Il metodo restituis e
altrimenti.

true

se l'elemento stato inserito nell'albero,

false

EA. Eser izi su alberi binari

21

EA.6 Somma
Soluzione a pag. 81

Dotare la lasse

AlberoBinario

(vedi EA.1) del metodo

Somma()

se ondo

la seguente spe i a.
Nome

Param. Ingr.

Param. Us .

Somma()

TElem

Somma ad ogni elemento dell'albero il valore intero spe i ato ome


parametro di ingresso.

EA.7 Sostituis i
Soluzione a pag. 81

Dotare la lasse

AlberoBinario

(vedi EA.1) del metodo

Sostituis i()

se ondo la seguente spe i a.


Nome

Sostituis i()
Detti i e j i parametri
o orrenze dell'elemento

Param. Ingr.

Param. Us .

TElem,TElem

unsigned int

di ingresso al metodo, sostituis e tutte le

on l'elemento

j.

Restituis e il numero di

sostituzioni eettuate.
N.B.: questo metodo in generale non preserva la propriet di ordinamento
dell'albero.

Si assuma omunque he questo metodo agis a sempre su un

albero ordinato.

EA.8 Conta Min e Max


Soluzione a pag. 82

Dotare la lasse

AlberoBinario

(vedi EA.1) del metodo

ContaMinMax(),

se ondo la seguente spe i a.


Nome

Param. Ingr.

Param. Us .

ContaMinMax()

TElem,TElem

unsigned int

Restituis e il numero degli elementi presenti nell'albero il ui valore


ompreso tra gli interi
estremi in lusi.

Min

Max

passati in ingresso al metodo,

EA. Eser izi su alberi binari

22

EA.9 Profondit Maggiore di Due


Soluzione a pag. 87

Dotare la lasse

AlberoBinario (vedi EA.1) del metodo ProfMaggioreDiDue()

se ondo la seguente spe i a.


Nome

Param. Ingr.

Param. Us .

ProfMaggioreDiDue()

bool

Predi ato he indi a se la profondit dell'albero strettamente maggiore di 2. Restituis e

false

true nel aso in ui la ondizione sia veri ata,

altrimenti.

EA.10 Profondita Maggiore Di


Soluzione a pag. 88

Dotare la lasse

AlberoBinario (vedi EA.1) del metodo ProfMaggioreDi()

se ondo la seguente spe i a.


Nome

Param. Ingr.

Param. Us .

ProfMaggioreDi()

unsigned int

bool

Predi ato he indi a se la profondit dell'albero strettamente maggiore del valore intero rappresentato dal parametro di ingresso. Restituis e

true

nel aso in ui la ondizione sia veri ata,

false

altrimenti.

EA.11 Profondit Massima


Soluzione a pag. 88

Dotare la lasse

AlberoBinario

(vedi EA.1) del metodo

Profondita(),

se ondo la seguente interfa ia.


Nome

Param. Ingr.

Param. Us .

Profondita()

TElem

int,bool

Restituis e la profondit dell'elemento spe i ato dal parametro di


ingresso.

In aso di o orrenze multiple, restituis e la profondit

massima. Restituis e inoltre un valore booleano he informa se tale


elemento o meno una foglia dell'albero. Nel aso in ui l'elemento
non fosse presente nell'albero, il metodo restituis e il valore -1.

EA. Eser izi su alberi binari

23

EA.12 Somma Livello


Soluzione a pag. 89

Dotare la lasse

AlberoBinario

(vedi EA.1) del metodo

SommaLivello()

se ondo la seguente spe i a.


Nome

Param. Ingr.

Param. Us .

SommaLivello()

TElem

Somma ad ogni elemento dell'albero un valore intero pari al livello


del orrispondente nodo. Per es.: al nodo radi e verr aggiunto 1, ai
suoi gli diretti 2. . . e .
N.B.: questo metodo in generale non preserva la propriet di ordinamento
dell'albero.

EA.13 Eliminazione Foglia


Soluzione a pag. 89

Dotare la lasse

AlberoBinario

(vedi EA.1) del metodo

EliminaFoglia()

se ondo la seguente spe i a.


Nome

Param. Ingr.

Param. Us .

EliminaFoglia()

TElem

bool

Elimina dall'albero l'elemento spe i ato se e solo se esso presente


ed una foglia. Il metodo restituis e
eettuata,

false

true

in aso di eliminazione

altrimenti.

EA.14 Eliminazione Foglie


Soluzione a pag. 94

Dotare la lasse

AlberoBinario

(vedi EA.1) del metodo

EliminaFoglie()

se ondo la seguente spe i a.


Nome

Param. Ingr.

Param. Us .

EliminaFoglie()

unsigned int

Elimina dall'albero tutte le foglie. Restituis e il numero di elementi


eliminati.

EA. Eser izi su alberi binari

24

EA.15 Operatore di Confronto


Soluzione a pag. 100

AlberoBinario

Dotare la lasse

(vedi EA.1) dell'operatore di onfronto,

se ondo la seguente spe i a.


Nome

Param. Ingr.

Param. Us .

operator==()

AlberoBinario

bool

l'operatore di onfronto tra alberi. Permette di valutare l'esatta


uguaglianza di due alberi. Fornis e

true

se esso stesso risulta essere

perfettamente uguale all'albero in ingresso (an he strutturalmente),

false

altrimenti.

EA.16 Conta Nodi non Foglia


Soluzione a pag. 100

Dotare la lasse

AlberoBinario (vedi EA.1) del metodo ContaNodiNonFoglia()

se ondo la seguente spe i a.


Nome

Param. Ingr.

Param. Us .

ContaNodiNonFoglia()

unsigned int

Restituis e il numero di nodi non foglia presenti nell'albero.

EA.17 Conta Nodi


Soluzione a pag. 101

Dotare la lasse

AlberoBinario

(vedi EA.1) del metodo

ContaNodi()

ondo la seguente spe i a.


Nome

Param. Ingr.

Param. Us .

ContaNodi()

unsigned int,
unsigned int,
unsigned int

Restituis e il numero di nodi dell'albero aventi 0,


rispettivamente.

1 e 2 gli,

se-

Capitolo EP
Eser izi su pile
EP.1 Push Greater
Soluzione a pag. 107

Si realizzi in linguaggio C++ il tipo di dato astratto

Pila

mediante uso del

lass del linguaggio e ri orrendo ad un'implementazione dinami a.


TElem degli elementi della pila sia il tipo int.

ostrutto
Il tipo

Di seguito riportata la spe i a dei metodi pubbli i da implementare


per la lasse

Pila.

Nome

Param. Ingr.

Param. Us .

Pila()

TElem

Costruttore senza parametri.

Pila()
Distruttore.

Push()

Aggiunge sulla pila l'elemento spe i ato.

PushGreater()

TElem

bool

Aggiunge sulla pila l'elemento spe i ato es lusivamente se esso


maggiore dell'elemento di testa orrente. Nel aso in ui la pila sia
vuota l'aggiunta sempre eseguita. Restituis e

true oppure false a

se onda he l'aggiunta sia stata eseguita oppure no.

Top()

TElem

Restituis e l'elemento di testa orrente della pila (ma non lo estrae).


In aso di pila vuota il omportamento di questo metodo non
spe i ato.
25

EP. Eser izi su pile


Pop()

26

TElem

Estrae e restituis e l'elemento di testa orrente della pila. In aso di


pila vuota il omportamento di questo metodo non spe i ato.

Svuota()

int

Svuota la pila.

Count()

Restituis e il numero di elementi presenti nella pila.

Empty()

bool

Predi ato vero se la pila vuota, falso altrimenti.


Si realizzi una funzione

main() he permetta di eettuare il ollaudo della

struttura dati realizzata.


Nessuno dei metodi della lasse pu utilizzare operazioni he oinvolgono
gli stream di input ed output ( in e

out).

La s rittura e la lettura su stream

sono on esse es lusivamente all'interno del programma

main().

Capitolo EC
Eser izi su ode
EC.1 Coda
Soluzione a pag. 111

Si realizzi in linguaggio C++ il tipo di dato astratto

Coda

mediante uso del

lass del linguaggio e ri orrendo ad un'implementazione dinami a.


TElem degli elementi della oda sia il tipo int.

ostrutto
Il tipo

Di seguito riportata la spe i a dei metodi pubbli i da implementare


per la lasse

Coda.

Nome

Param. Ingr.

Param. Us .

Coda()

TElem

TElem

Costruttore senza parametri.

Coda()
Distruttore.

Push()
A oda l'elemento spe i ato.

Top()

Restituis e l'elemento di testa orrente della oda (ma non lo estrae).


In aso di oda vuota il omportamento di questo metodo non
spe i ato.

Pop()

TElem

Estrae e restituis e l'elemento di testa orrente presente in oda.


In aso di oda vuota il omportamento di questo metodo non
spe i ato.

27

EC. Eser izi su ode

28

Somma()

TElem

Restituis e la somma di tutti gli elementi presenti in oda.

Svuota()

int

Svuota la oda.

Count()

Restituis e il numero di elementi presenti nella oda.

Empty()

bool

Predi ato vero se la oda vuota, falso altrimenti.


Si realizzi una funzione

main() he permetta di eettuare il ollaudo della

struttura dati realizzata.


Nessuno dei metodi della lasse pu utilizzare operazioni he oinvolgono
gli stream di input ed output ( in e

out).

La s rittura e la lettura su stream

sono on esse es lusivamente all'interno del programma

main().

EC.2 Coda on Perdite


Soluzione a pag. 115

Si realizzi in linguaggio C++ il tipo di dato astratto


ostrutto
tipo

int.

lass

del linguaggio. Il tipo

TElem

Coda

mediante uso del

degli elementi della oda sia il

Di seguito riportata la spe i a dei metodi pubbli i da implementare


per la lasse

Coda.

Nome

Param. Ingr.

Param. Us .

Coda()

unsigned int

Costruttore on parametro intero. Il parametro indi a il numero massimo di posti in oda, oltre il quale non deve essere possibile inserire
ulteriori elementi.

Coda()

Distruttore.

Push()

TElem

A oda l'elemento spe i ato. Restituis e


a odato,

false

altrimenti.

true

bool
in aso di elemento

EC. Eser izi su ode

29

Top()

TElem

Restituis e l'elemento di testa orrente della oda (ma non lo estrae).


In aso di oda vuota il omportamento di questo metodo non
spe i ato.

Pop()

TElem

Estrae e restituis e l'elemento di testa orrente presente in oda.


In aso di oda vuota il omportamento di questo metodo non
spe i ato.

Pop()

unsigned int

TElem

Estrae tanti elementi quanti spe i ati dal parametro di ingresso e


restituis e solo il primo di questi, io l'elemento presente in testa
pre edentemente alla hiamata al metodo. Rappresenta una versione
overloaded del metodo pre edente.

Nel aso in ui la oda risulti

vuota all'atto della hiamata al metodo, il omportamento risultante


non spe i ato.

Svuota()

int

Svuota la oda.

Count()

Restituis e il numero di elementi presenti nella oda.

Empty()

bool

Predi ato vero se la oda vuota, falso altrimenti.


Si realizzi una funzione

main() he permetta di eettuare il ollaudo della

struttura dati realizzata.


Nessuno dei metodi della lasse pu utilizzare operazioni he oinvolgono
gli stream di input ed output ( in e

out).

La s rittura e la lettura su stream

sono on esse es lusivamente all'interno del programma

main().

EC.3 Coda a Priorit


Soluzione a pag. 119

Si realizzi in linguaggio C++ il tipo di dato astratto

lass del linguaggio. Il tipo


int. La struttura permette di a odare

diante uso del ostrutto


della oda sia il tipo

PriorityQueue meTElem degli elementi

possono avere due dierenti livelli di priorit:

high (alta) e low

elementi he
(bassa). Un

elemento a bassa priorit viene sempre a odato alla struttura. Un elemento

EC. Eser izi su ode

30

a priorit alta ha inve e la pre edenza sugli elementi a priorit bassa, ma


non sugli elementi a priorit alta eventualmente gi presenti nella struttura.
Di seguito riportata la spe i a dei metodi pubbli i da implementare
per la lasse

Coda.

Nome

Param. Ingr.

Param. Us .

PriorityQueue()

TElem

Costruttore.

PriorityQueue()
Distruttore.

PushLow()

Aggiunge un elemento a bassa priorit. L'elemento viene aggiunto in


oda alla struttura.

PushHigh()

TElem

Aggiunge un elemento ad alta priorit. L'elemento viene aggiunto di


seguito ad eventuali elementi a priorit alta gi presenti oppure, in
loro assenza, in testa alla struttura.

Pop()

TElem

Estrae e restituis e l'elemento di testa orrente presente in oda.


In aso di oda vuota il omportamento di questo metodo non
spe i ato.

Svuota()

bool

Svuota la oda.

Empty()

Predi ato vero se la oda vuota, falso altrimenti.


Si realizzi una funzione

main() he permetta di eettuare il ollaudo della

struttura dati realizzata.


Nessuno dei metodi della lasse pu utilizzare operazioni he oinvolgono
gli stream di input ed output ( in e

out).

La s rittura e la lettura su stream

sono on esse es lusivamente all'interno del programma

main().

EC.4 PopMinMax
Soluzione a pag. 124

Dotare la lasse

Coda (vedi EC.1) dei metodi PopMax() e PopMin() se ondo

la seguente spe i a.

EC. Eser izi su ode

31

Nome

Param. Ingr.

Param. Us .

PopMax()
Detto n il

unsigned int

TElem

valore del parametro di ingresso di tipo intero, il metodo

estrae i primi

n valori di testa della struttura e restituis e il massimo

tra questi. In aso di oda vuota il omportamento di questo metodo


non spe i ato.

PopMin()
Detto n il

unsigned int

TElem

valore del parametro di ingresso di tipo intero, il metodo

estrae i primi

valori di testa della struttura e restituis e il minimo

tra questi. In aso di oda vuota il omportamento di questo metodo


non spe i ato.

Capitolo EX
Altri eser izi
EX.1 A umulatore
Soluzione a pag. 125

Si realizzi la lasse

A umulatore

onforme all'interfa ia seguente.

Nome

Param. Ingr.

Param. Us .

A umulatore()

float

Costruttore della lasse.

Add()

Aggiunge all'a umulaotre il valore spe i ato dal parametro di


ingresso.

Reset()

float

Azzera l'a umulatore.

GetValue()

Restituis e il valore orrente dell'a umulatore.

EX.2 Cifratore
Soluzione a pag. 126

Implementare la lasse

Cifratore

on la apa it di ifrare stringhe di a-

ratteri attraverso uno slittamento del odi e ASCII dei aratteri omponenti
la stringa ( .d. odi e di Cesare). L'interfa ia della lasse sia la seguente:

32

EX. Altri eser izi

33

Nome

Param. Ingr.

Param. Us .

Cifratore()

int

Costruttore della lasse.

Imposta la ostante intera di slittamento

he il ifratore utilizza per rittografare le stringhe.

Cifra()

har

har

Metodo di ifratura. A etta la stringa da ifrare e ne restituis e la


versione ifrata. La ifratura onsiste in uno slittamento (shift) dei
odi i ASCII di ogni singolo arattere della stringa.

De ifra()

har

har

Metodo di de ifratura. A etta la stringa ifrata attraverso il metodo

Cifra()

e ne restituis e nuovamente la versione de ifrata.

EX.3 Lista Della Spesa


Soluzione a pag. 127

ListaDellaSpesa
lass del linguaggio e ri orrendo ad un'implemen-

Si realizzi in linguaggio C++ il tipo di dato astratto


mediante uso del ostrutto

tazione dinami a. I metodi della struttura dati possono essere implementati


utilizzando indierentemente algoritmi iterativi o ri orsivi. Gli elementi della
lista siano del tipo

Arti olo

spe i ato di seguito:

typedef har Nome[20;


typedef float Quantita;
stru t Arti olo {
Nome n;
Quantita q;
};
Di seguito si riporta la spe i a dei metodi da implementare.
Nome

Param. Ingr.

Param. Us .

ListaDellaSpesa()

Costruttore.

ListaDellaSpesa()
Distruttore.

EX. Altri eser izi

34

Aggiungi()

Nome,Quantita

Quantita

Se nella lista non gi presente al un altro elemento on lo stesso


nome, inseris e l'elemento spe i ato (nella quantit spe i ata) in
oda alla lista. Nel aso in ui inve e l'elemento fosse gi presente
nella lista, vi aggiunge la quantit spe i ata.
Il metodo restituis e la quantit on ui l'arti olo spe i ato
presente nella lista in seguito all'aggiunta.

Elimina()

Nome

bool

Elimina dalla lista l'elemento avente il nome spe i ato (se presente).
Il metodo restituis e

true

se stato an ellato un elemento,

false

altrimenti.

GetQuantita()

Nome

Quantita

Restituis e la quantit dell'elemento presente nella lista ed avente il


nome spe i ato. Se l'elemento non presente restituis e zero.

Svuota()

Svuota la lista.

Stampa()

Stampa il ontenuto dell'intera lista nel formato

Nome:

Quantit, ...

Nome:

Quantit,

ListaDellaSpesa he pu utilizzare lo standardStampa(). Gli altri metodi (pubbli i, privati o

L'uni o metodo della lasse


output ( out) il metodo

protetti) non possono fare uso delle funzionalit di stampa.


Si realizzi una funzione

main() he permetta di eettuare il ollaudo della

struttura dati realizzata.

EX.4 Predittore di Temperatura


Soluzione a pag. 131

Realizzare la lasse
temperatura.

TempPredi tor

he svolga la funzione di predittore di

Tale oggetto deve essere apa e di fornire una stima della

temperatura in un erto istante futuro di tempo.

La stima operata a

partire da dati presenti e passati forniti dall'utente sui valori di temperatura


misurati attraverso ipoteti i sensori.
Si supponga he la stima sia ottenuta mediante estrapolazione lineare
delle ultime due temperature fornite dall'utente della lasse.

Per esempio,

se l'utente omuni a all'oggetto he la temperatura all'istante 0 pari a 14

EX. Altri eser izi

35

e he all'istante 5 pari a 16 , una ri hiesta della stima della temperatura

all'istante 10 produrrebbe ome risultato 18 .


Si onsideri la seguente interfa ia della lasse.
Nome

Param. Ingr.

Param. Us .

TempPredi tor()

Time,Temp

Costruttore della lasse. A etta in ingresso una prima lettura reale


della temperatura, insieme all'istante in ui questa stata ampionata
da un ipoteti o sensore.

SetTemp()

Time,Temp

Fornis e al predittore un ulteriore valore di temperatura ampionato


ed il relativo istante di ampionamento.

EstimateTemp()

Time

Temp

Ri hiede al predittore di eettuare una stima della temperatura in


un parti olare istante di tempo spe i ato.
Il ostruttore a etta in ingresso un primo valore della temperatura ad
un erto istante di tempo.

In assenza di altri dati la stima sar pari pro-

prio a questo valore. Qualsiasi hiamata ad

EstimateTemp(),

io, fornir

ome risultato il valore di temperatura spe i ato all'atto della hiamata

del ostruttore . Su essivamente l'utente omuni her all'oggetto nuovi valori della temperatura attraverso ripetute hiamate al metodo

SetTemp(),

spe i andone an he i relativi istanti di tempo.

EX.5 Contenitore
Soluzione a pag. 133

Si realizzi in linguaggio C++ il tipo di dato astratto


diante uso del ostrutto

lass del linguaggio.

Contenitore

me-

Un Contenitore pu ontenere

istanze del tipo Oggetto, denito ome segue:

onst int NMAX = 50;


typedef har Nome[NMAX;
typedef int Peso;
stru t Oggetto {
1 Ci

permette al predittore di operare non appena sia disponibile un primo


ampionamento della temperatura.

EX. Altri eser izi

};

36

Nome n;
Peso p;

Inoltre, ogni ontenitore pu ospitare oggetti no al raggiungimento di


un peso omplessivo massimo, oltre il quale nessun altro oggetto pu essere
ospitato.
Di seguito riportata la spe i a dei metodi pubbli i da implementare
per la lasse

Contenitore.

Nome

Param. Ingr.

Param. Us .

Contenitore()

Peso

Costruttore on parametro di tipo

Peso.

Il parametro indi a il

peso massimo raggiungibile dalla totalit degli oggetti presenti nel


ontenitore.

Contenitore()

Nome,Peso

bool

Distruttore.

Inseris i()

Inseris e nel ontenitore un oggetto avente il nome e il peso spe i ato. Il metodo restituis e

true

se l'inserimento va a buon ne, io

se il peso dell'elemento da inserire non e ede la apa it residua del


ontenitore,

false

altrimenti.

Svuota()

Svuota il ontenitori di tutti gli oggetti presenti in esso.

PesoComplessivo()

Peso

Restituis e il peso omplessivo raggiunto dal ontenitore.

PesoResiduo()

Peso

Restituis e il peso residuo per il raggiungimento della apa it


massima del ontenitore.

NumElem()

unsigned int

Restituis e il numero di oggetti presenti nel ontenitore.

Stampa()

Stampa le oppie (Nome, Peso) di tutti gli oggetti presenti nel


ontenitore.

EX. Altri eser izi

37

Contenitore
Stampa(). Gli

L'uni o metodo (pubbli o, privato o protetto) della lasse

he pu utilizzare lo standard-output ( out) il metodo

altri metodi dovranno restituire l'esito delle operazioni eseguite mediante gli
opportuni parametri di passaggio riportati nelle spe i he.

EX.6 Lista Prenotazioni


Soluzione a pag. 136

Si realizzi in linguaggio C++ il tipo di dato astratto


mediante uso del ostrutto

lass

ListaPrenotazioni

del linguaggio. La lista deve memorizzare

le prenotazioni di studenti ad un generi o evento (uno ed uno solo).


elementi della lista siano del tipo

Prenotazione

Gli

spe i ato di seguito:

typedef int Matri ola;


typedef har Nome[30;
stru t Prenotazione {
Matri ola mat;
Nome nom;
};
I metodi da implementare per la lasse

ListaPrenotazioni

siano on-

formi alla seguente interfa ia.


Nome

Param. Ingr.

Param. Us .

ListaPrenotazioni()

int

Costruttore on parametro intero. Il parametro indi a il numero massimo di posti disponibili per l'evento, oltre i quali non deve essere
possibile inserire ulteriori prenotazioni.

ListaPrenotazioni()

Matri ola,Nome

bool

Distruttore.

Prenota()

Se nella lista non gi presente al una altra prenotazione on lo


stesso numero di matri ola e se i sono posti disponibili, inseris e
una nuova prenotazione in oda alla lista. Il metodo restituis e l'esito
dell'operazione.

EliminaPrenotazione()

Matri ola

boolt

Elimina dalla lista la prenotazione relativa al ampo matri ola spe i ato (se presente). Il metodo restituis e
un elemento,

false

altrimenti.

true

se stato eliminato

EX. Altri eser izi

38

GetPostiDisponibili()

int

Restituis e il numero di posti an ora disponibili.

EsistePrenotazione()
Matri ola
Restituis e true se esiste la prenotazione
matri ola spe i ato, false altrimenti.
Svuota()

bool
relativa al numero di

Svuota la lista.

Stampa()
Stampa

il

Matri ola1:
Nome3, ...

ontenuto

dell'intera

Nome1, Matri ola2:

lista

nel

formato

seguente:

Nome2, Matri ola3:

ListaPrenotazioni he pu utilizzare lo
metodo Stampa(). Gli altri metodi (pubbli i,

L'uni o metodo della lasse


standard-output ( out) il

privati o protetti) non possono fare uso degli stream di I/O.


Si realizzi una funzione

main() he permetta di eettuare il ollaudo della

struttura dati realizzata.

EX.7 Classi a
Soluzione a pag. 140

Si realizzi in linguaggio C++ il tipo di dato astratto


uso del ostrutto

lass del linguaggio.

Classifi a

mediante

L'implementazione deve essere realiz-

zata mediante puntatori ed allo azione dinami a della memoria. Gli elementi
della lista siano di tipo

TElem,

denito nel modo seguente:

onst int NMAX = 50;


typedef har Nome[NMAX; //Nome delle squadre
typedef stru t {
Nome n;
unsigned int punteggio;
} Squadra;
typedef Squadra TElem;
Di seguito riportata la spe i a dei metodi pubbli i da implementare
per la lasse

Classifi a.

EX. Altri eser izi

39

Nome

Param. Ingr.

Param. Us .

Classifi a()

Nome,unsigned
int

unsigned int

Costruttore.

Classifi a()
Distruttore.

Aggiungi()

Se la squadra non gi presente, la aggiunge alla struttura e le assegna il punteggio spe i ato. Nel aso di squadra gi presente, aggiunge il punteggio spe i ato a quello gi totalizzato. Restituis e il
numero di punti orrentemente totalizzati dalla squadra.

Svuota()

Svuota la struttura.

Stampa()

Stampa la lassi a delle squadre presenti nella struttura, in ordine


de res ente di punteggio.

Count()

unsigned int

Conta gli elementi ontenuti nella struttura.

Classifi a he pu utilizzare lo standardStampa(). Gli altri metodi (pubbli i, privati o

L'uni o metodo della lasse


output ( out) il metodo

protetti) non possono fare uso degli oggetti per l'I/O.


Si realizzi una funzione

main() he permetta di eettuare il ollaudo della

struttura dati realizzata.


Suggerimento: l'aggiornamento di un punteggio nella struttura pu essere
onvenientemente realizzato attraverso la omposizione di un'eliminazione ed
un inserimento ordinato.

EX.8 Agenzia Matrimoniale


Soluzione a pag. 144

Si realizzi in linguaggio C++ il tipo di dato astratto


mediante uso del ostrutto

lass

del linguaggio.

AgenziaMatrimoniale

L'implementazione deve

essere realizzata mediante puntatori ed allo azione dinami a della memoria.


Gli elementi della lista siano di tipo

TElem,

denito nel modo seguente:

EX. Altri eser izi

40

onst int NMAX = 50;


typedef har Nome[NMAX; //Nome Persona
stru t persona;
typedef stru t Persona{
Nome n;
bool mas hio;
Persona* oniuge;
};
typedef Persona TElem;
Di seguito riportata la spe i a dei metodi pubbli i da implementare
per la lasse

AgenziaMatrimoniale.

Nome

Param. Ingr.

Param. Us .

AgenziaMatrimoniale()

Nome,bool

bool

Costruttore.

AgenziaMatrimoniale ()
Distruttore.

AggiungiPersona()

Aggiunge alla struttura la persona avente nome spe i ato attraverso


i parametri di ingresso, e indi a se mas hio (parametro di ingresso

true) o femmina (parametro di ingresso pari


stituis e true in aso di inserimento avvenuto, false
pari a

false)

Re-

altrimenti (se

esiste gi una persona on lo stesso nome).

Sposa()

Nome,Nome

bool

Mar a ome sposate le due persone presenti nella struttura ed aventi nomi spe i ati dai parametri di ingresso.

Restituis e l'esito

dell'operazione. L'operazione fallis e nei asi seguenti:

uno o entrambi i nomi non sono presenti nella lista;

le persone spe i ate sono dello stesso sesso;

una o entrambe le persone risultano gi sposate.

EX. Altri eser izi

41

Coniugato()

Nome

bool, bool

Restituis e due valori booleani. Il primo indi a se il nome spe i ato


presente o meno nella lista. Se tale valore vero, il se ondo valore
restituito pari a vero se la persona dal nome spe i ato oniugata,
falso altrimenti.

NumeroSposi()

unsigned int

Restituis e il numero delle persone oniugate nella struttura.

NumeroCoppie()

unsigned int

Restituis e il numero di oppie di sposi presenti nella struttura.

Svuota()

Svuota la struttura.

Stampa()

Stampa il ontenuto della struttura (vedi esempio ???).

AgenziaMatrimoniale he pu utilizzare lo
metodo Stampa(). Gli altri metodi (pubbli i,

L'uni o metodo della lasse


standard-output ( out) il

privati o protetti) non possono fare uso degli oggetti per l'I/O.
Si realizzi una funzione

main() he permetta di eettuare il ollaudo della

struttura dati realizzata.

EX.9 Par o Pattini


Soluzione a pag. 148

La ditta Sax gestis e una pista di pattinaggio e dispone di un par o


pattini. I pattini, tutti dello stesso modello, vengono ttati ai lienti a tempo,
in base alla taglia della alzatura ri hiesta. Si implementi in linguaggio C++
la lasse

Par oPattini

utile ad una prima automatizzazione nella gestione

della pista. Data la denizione del tipo Taglia:

typedef unsigned int Taglia;


si implementi la struttura onformemente all'interfa ia spe i ata di
seguito.
Nome

Param. Ingr.

Param. Us .

Par oPattini()

Costruttore senza parametri. Inizializza una struttura he ontiene


un par o pattini vuoto.

EX. Altri eser izi

42

Par oPattini()

Taglia

Distruttore.

AggiungiPattini()

Aggiunge al par o un paio di pattini della misura spe i ata.

Svuota()

unsigned int

Svuota il par o pattini.

NumeroTotPattini()

Restituis e il numero di paia di pattini he ostituis ono l'intero


par o.

Fitta()

Taglia

bool

Mar a ome ttati un paio di pattini della taglia spe i ata dal

true se esiste almeno un


false altrimenti.

parametro di ingresso. Il metodo restituis e


paio di pattini della taglia spe i ata,

Disponibilita()

Taglia

unsigned int

Restituis e il numero di paia di pattini disponibili per la taglia


spe i ata.

NumeroPattini()

Taglia

unsigned int

Restituis e il numero di paia di pattini appartenenti al par o, di data


taglia (indipendentemente dal loro stato).

Restituzione()

Taglia

bool

Mar a nuovamente ome disponibile un paio di pattini della taglia


spe i ata. Il metodo restituis e

true

se eettivamente esisteva un

paio di pattini della taglia spe i ata mar ati ome ttati,

false

altrimenti.

Stampa()

Stampa a video lo stato dell'intero par o pattini.

EX.10 Timer
Soluzione a pag. 154

Si realizzi la lasse

Timer

he svolga le funzioni di ronometro.

Tale og-

getto deve poter gestire i messaggi START, STOP, RESET e GETTIME


omportandosi ome spe i ato dall'interfa ia seguente.

IL TIMER VIENE CREATO

EX. Altri eser izi

43

INATTIVO

10

GETTIME

START

ATTIVO

10

15

20

INATTIVO

15

GETTIME GETTIME

25

30

35

40

STOP

GETTIME

RESET

GETTIME

Valori conteggio

Figura EX.1: Un esempio d'uso del timer nel tempo

Nome

Param. Ingr.

Param. Us .

Start()

Time

Avvia il onteggio del tempo.

Stop()
Arresta il onteggio del tempo.

Reset()
Arresta ed azzera il timer.

GetTime()

Restituis e il onteggio orrente del tempo.


Nella gura riportato un esempio gra o del funzionamento dell'oggetto.

Suggerimenti

La seguente riga di odi e:

time t = time(0);
istanzia una variabile

di tipo

sistema, restituito dalla funzione

time e la pone uguale


time(), sotto la forma

al tempo di
di un intero

he rappresenta il numero di se ondi tras orsi dalla mezzanotte del 1


gennaio 1970. La funzione

time()

presente nella libreria C

time.h.

Il funzionamento del timer nei asi non espressamente previsti dalle


spe i he sia arbitrario.

EX. Altri eser izi

44

EX.11 Timer Avanzato


Soluzione a pag. 155

Con riferimento alla lasse

Timer

dell'eser izio EX.10, si onsiderino le se-

guenti ulteriori spe i he:

quando il timer ri eve il messaggio START, il onteggio non deve


ripartire sempre da 0, ma dal valore orrentemente memorizzato;

la ri ezione di un messaggio START a timer attivo deve essere ininuente;

la ri ezione di un messaggio STOP a timer fermo deve essere ininuente.

Modi are, se ne essario, l'implementazione del timer per rendere la lasse onforme a queste ulteriori spe i he.

EX.12 Votazioni
Soluzione a pag. 157

Si supponga di voler gestire un exit-poll elettorale.

Ad ogni intervistato

all'us ita dal seggio si hiede il partito per ui ha votato. In ogni momento
bisogna poi essere in grado di dire quanti voti ha ottenuto ias un partito
e qual la distribuzione dei voti tra i partiti. Mediante l'uso del ostrutto

lass

del linguaggio C++, si realizzi una struttura dati adatta all'uopo.

Si supponga, per sempli it, he ogni partito identi ato on un odi e


intero, e si ignorino i voti bian hi e nulli. Di seguito riportata la spe i a
dei metodi pubbli i da implementare per la lasse

Votazioni.

Nome

Param. Ingr.

Param. Us .

Votazioni()

unsigned int

unsigned int

Costruttore.

Votazioni()
Distruttore.

AggiungiVoto()

Aggiunge un voto al partito avente il odi e spe i ato dal parametro di ingresso. Restituis e il numero di voti a umulati no a quel
momento dal partito.

Svuota()
Svuota la struttura.

EX. Altri eser izi

45

GetVotiPartito()

unsigned int

unsigned int

Restituis e il numero di voti ottenuto dal partito avente il odi e


spe i ato dal parametro di ingresso.

GetNumeroVoti()

unsigned int

Restituis e il numero totale di voti.

GetSituazione()

Stampa a video un riepilogo dei voti omplessivamente registrati nella


struttura.

Votazioni he
GetSituazione().

L'uni o metodo della lasse


output ( out) il metodo

pu utilizzare lo standardGli altri metodi (pubbli i,

privati o protetti) non possono fare uso delle funzionalit di stampa.


Si realizzi una funzione
struttura dati realizzata.

main() he permetta di eettuare il ollaudo della

Parte II
Soluzioni

46

Capitolo SL
Soluzioni degli eser izi su liste
SL.1 Lista Sempli emente Collegata
Tra ia a pag. 12

File Lista.h

#ifndef _LISTA_H_
#define _LISTA_H_
stru t Re ord ;
typedef Re ord PRe ;
typedef int TElem ;
stru t Re ord {
};

TElem e l ;
PRe s u ;

lass L i s t a {
private :
PRe f i r s t ;
int ount ;
publi :
L i s t a ( ) ; // o s t r u t t o r e
L i s t a ( onst L i s t a& l ) ;

~ L i s t a ( ) ; // d i s t r u t t o r e

};

senza parametri
// o s t r u t t o r e d i o p i a

void I n s e r i s i ( onst TElem& e l ) ; // I n s e r i m e n t o i n t e s t a


int NumeroElementi ( ) onst ; // R e s t i t u i s e i l numero d e g l i e l e m e n t i n e l l a
void Svuota ( ) ; // Svuota l a l i s t a
void Elimina ( onst TElem& e l ) ; // Elimina un elemento s e p r e s e n t e
void Stampa ( ) onst ; // Stampa su s t . out . t u t t i g l i e l e m e n t i
bool R i e r a ( onst TElem& e l ) onst ; // I n d i a l a p r e s e n z a d i un elemento

#endif

/ _LISTA_H_ /

47

lista

SL. Soluzioni degli eser izi su liste

48

File Lista. pp

#in lude <i o s t r e a m>


#in lude " l i s t a . h"
using namespa e s t d ;
L i s t a : : L i s t a ( ) : f i r s t ( 0 ) , ount ( 0 ) {
}

onst
new

Lista : : Lista (
L i s t a& l ) : f i r s t ( 0 ) , ount ( l . ount ) {
( l . f i r s t ) { // s e l a l i s t a l vuota non e s e g u e al una o p e r a z i o n e
first =
Re ord ;
f i r s t >e l = l . f i r s t >e l ;

if

PRe l p = l . f i r s t ;
PRe p = f i r s t ;
( lp >s u ) {
Re ord ;
p>s u =

while

new

p = p>s u ;
l p = lp >s u ;

p>e l = lp >e l ;
}
p>s u = 0 ; // imposta a 0 i l su d e l l ' u l t i m o elemento d e l l a l i s t a

Lista ::~ Lista () {


Svuota ( ) ;
}

void

Lista : : I n s e r i s i (
PRe p =
Re ord ;
p>e l = e l ;
p>s u = f i r s t ;
first = p;

new

onst

TElem& e l ) {

ount++;

int L i s t a : : NumeroElementi ( ) onst


return ount ;

void L i s t a : : Svuota ( )
PRe tbd ;
while ( f i r s t ) {
}
}

tbd = f i r s t ;
f i r s t = f i r s t >s u ;
tbd ;

delete

ount = 0 ;

void
if

onst

L i s t a : : Elimina (
TElem& e l ) {
( f i r s t ) { // l a l i s t a non vuota
( f i r s t >e l == e l ) { // l ' elemento da e l i m i n a r e i n t e s t a
PRe tbd = f i r s t ; // t b d = t o be d e l e t e d

if

SL. Soluzioni degli eser izi su liste

49

f i r s t = f i r s t >s u ;
tbd ;
ount ;

delete
}

else { // l ' elemento da e l i m i n a r e non


PRe p = f i r s t ;
bool t r o v a t o = false ;
while ( ( p>s u ) && ( ! t r o v a t o ) ) {
// l ' elemento s u e s s i v o a q u e l l o
if ( p>su >e l == e l ) {

in t e s t a

p u n t a t o da p deve e s s e r e e l i m i n a t o

PRe tbd = p>s u ;


p>s u = tbd >s u ; // s o l l e g a l ' elemento t b d . . .
tbd ; // . . . e l o e l i m i n a

delete

trovato =
ount ;

else

true ;

p = p>s u ;

void

L i s t a : : Stampa ( )
PRe p = f i r s t ;

onst

while
}

(p) {
out << p>e l << " " ;
p = p>s u ;

bool L i s t a : : R i e r a ( onst TElem&


PRe p = f i r s t ;
bool t r o v a t o = false ;
while ( ( p ) && ( ! t r o v a t o ) ) {
if ( p>e l == e l )
t r o v a t o = true ;
else
}
}

el )

onst

p = p>s u ;

return

trovato ;

File main. pp

#in lude <i o s t r e a m>


#in lude <s t d l i b . h>
#in lude " l i s t a . h"
using namespa e s t d ;
// P r o t o t i p i d i f u n z i o n i d i s u p p o r t o per l a v e r i f i a d e l
// o r r e t t o funzionamento d e i metodi d e l l a l a s s e L i s t a .
stampaMenu ( ) ;
I n s e r i s i ( L i s t a& l ) ;
R i e r a ( L i s t a& l ) ;
Elimina ( L i s t a& l ) ;

void
void
void
void

SL. Soluzioni degli eser izi su liste

void Svuota ( L i s t a& l ) ;


void NumeroElementi ( L i s t a&
void Stampa ( L i s t a& l ) ;
void C o p i a L i s t a ( L i s t a& l ) ;
int main ( )
{
har ;

l );

Lista l i s t a ;

do

swit h ( ) {
ase ' 1 ' :
Inseris i ( lista );
break ;
ase ' 2 ' :
Ri er a ( l i s t a ) ;
break ;
ase ' 3 ' :
Elimina ( l i s t a ) ;
break ;
ase ' 4 ' :
Svuota ( l i s t a ) ;
break ;
ase ' 5 ' :
Stampa ( l i s t a ) ;
break ;
ase ' 6 ' :
NumeroElementi ( l i s t a ) ;
break ;
ase ' 7 ' :
CopiaLista ( l i s t a ) ;
break ;
ase ' 8 ' :
break ;
default :
out << " S e l t a non v a l i d a . \ n" ;
break ;
}
} while ( != ' 8 ' ) ;
return 0 ;

void

{
stampaMenu ( ) ;
i n >> ;
in . ignore ( ) ;

stampaMenu ( ) {
out << e n d l ;
out << " 1 . I n s e r i s i " << e n d l ;
out << " 2 . R i e r a " << e n d l ;
out << " 3 . Elimina " << e n d l ;
out << " 4 . Svuota " << e n d l ;
out << " 5 . Stampa" << e n d l ;
out << " 6 . Numero Elementi " << e n d l ;
out << " 7 . Copia " << e n d l ;
out << " 8 . E s i " << e n d l ;
out << e n d l ;
out << " S e l t a : " ;

50

SL. Soluzioni degli eser izi su liste

void I n s e r i s i ( L i s t a&
int i ;
}

51

l) {

out << " I n s e r i s i i n t e r o : " ;


i n >> i ;
l . Inseris i ( i );

void R i e r a ( L i s t a&
int i ;

l) {

out << " I n s e r i s i i n t e r o : " ;


i n >> i ;
( l . Ri er a ( i ))
out << " Trovato . \ n" ;

if
else

out << "Non t r o v a t o . \ n" ;

void Elimina ( L i s t a&


int i ;
}

l) {

out << " I n s e r i s i i n t e r o : " ;


i n >> i ;
l . Elimina ( i ) ;

void
}

Svuota ( L i s t a& l ) {
out << " Svuotamento l i s t a . " << e n d l ;
l . Svuota ( ) ;

void
}

Stampa ( L i s t a& l ) {
out << "Stampa : \ n" ;
l . Stampa ( ) ;
out << e n d l ;

void
}

NumeroElementi ( L i s t a& l ) {
out << "Numero Elementi : " << l . NumeroElementi ( ) << e n d l ;

void

C o p i a L i s t a ( L i s t a& l ) {
Lista l opia ( l ) ;

out << "La l i s t a o p i a t a o n t i e n e : " ;


l o p i a . Stampa ( ) ;
out << e n d l ;

Implementazione alternativa del metodo Lista::Elimina()


possibile realizzare un'implementazione alternativa del metodo

Elimina()

an ora pi sinteti a. Tale variante, a dierenza dell'implementazione pre edente, non dis rimina il aso in ui l'elemento da eliminare sia posizionato in
testa alla struttura, ma tratta tutti i asi in maniera omogenea. Per ottenere
questo, su iente utilizzare un puntatore a
 vedi Figura SL.1).
Inizialmente il puntatore

pp

PRe

denito del tipo

(puntatore a puntatore

PRe *

first, membro privato della lista (linea ontinua).

punta alla lo azione

Nella (eventuale) se onda

SL. Soluzioni degli eser izi su liste


pp

52

pp

first
el

count

succ

el

succ

el

succ

Lista
Figura SL.1: Un puntatore s orre la lista puntando ai puntatori ontenuti
in essa.

iterazione, esso passa a puntare alla lo azione

su

dell'elemento di testa

(linea tratteggiata), rispettando nel passaggio la ompatibilit di tipo.

void
if

onst

L i s t a : : Elimina (
TElem\& e l ) {
( f i r s t ) { // l a l i s t a non vuota
PRe pp = \& f i r s t ; // i n d i r i z z o d e l l a v a r i a b i l e f i r s t
trovato =
;
( ( pp ) \&\& ( ! t r o v a t o ) ) {
( ( pp)> e l == e l ) {
PRe tbd = pp ;
pp = ( pp)>s u ;
tbd ;

bool
while
if

false

delete

trovato =
ount ;

else

true ;

pp = \&(( pp)>s u ) ;

SL.2 Somma Elementi


Tra ia a pag. 13

onst

TElem L i s t a : : Somma( )
{
PRe p = f i r s t ;
TElem somma = 0 ;
(p) {
somma = somma + p>e l ;
p=p>s u ;
}

while

return

somma ;

SL. Soluzioni degli eser izi su liste

53

SL.3 Coda Pari


Tra ia a pag. 13

#in lude <i o s t r e a m>


#in lude <s t r i n g . h>
using namespa e s t d ;
stru t Re ord ;
typedef Re ord PRe ;
typedef int TElem ;
stru t Re ord {
};

TElem e l ;
PRe s u ;

lass L i s t a {
private :
PRe f i r s t ;
int nelem ;
PRe getPuntCoda ( )

onst ;

L i s t a ( onst L i s t a &); // v i e t a l a o p i a mediante o s t r u t t o r e


void operator= ( onst L i s t a &); // v i e t a l ' a s s e g n a z i o n e
publi :
Lista ( ) ;
~Lista ( ) ;

};

void I n s e r i s i ( TElem e l ) ;
void Svuota ( ) ;
void Stampa ( ) onst ;
int Count ( ) onst ;
bool SpostaTestaInCoda ( ) ;
bool CodaPari ( ) onst ;

L i s t a : : L i s t a ( ) : f i r s t ( 0 ) , nelem ( 0 ) {
}
Lista ::~ Lista () {
Svuota ( ) ;
}

void

L i s t a : : I n s e r i s i ( TElem e l ) {
// I n s e r i m e n t o i n t e s t a
PRe p =
Re ord ;
p>e l = e l ;
p>s u = f i r s t ;
first = p;

new

nelem++;

void L i s t a : : Svuota ( ) {
PRe tbd ; // t o be d e l e t e d
while ( f i r s t != 0) {
tbd = f i r s t ;
f i r s t = f i r s t >s u ;

SL. Soluzioni degli eser izi su liste

}
}

delete

tbd ;

nelem = 0 ;

void L i s t a : : Stampa ( ) onst


PRe p = f i r s t ;
while ( p != 0) {
}

54

out << p>e l << " " ;


p = p>s u ;

int L i s t a : : Count ( ) onst


return nelem ;

onst

PRe L i s t a : : getPuntCoda ( )
{
// R e s t i t u i s e i l p u n t a t o r e a l l a oda d e l l a l i s t a
( f i r s t ) { // non e s i s t e una oda s e l a l i s t a vuota ;
PRe p = f i r s t ;
( p>s u )
p = p>s u ;

if

while

return
else
return

}
}

p;
0;

bool L i s t a : : SpostaTestaInCoda ( ) {
PRe p = getPuntCoda ( ) ; // r e s t i t u i s e
if ( p ) {
}
}

i l punt . a l l a oda , s e ' .

p>s u = f i r s t ;
f i r s t = f i r s t >s u ;
p>su >s u = 0 ;

return

( p != 0 ) ; // s e p non 0 , l o spostamento s t a t o e f f e t t u a t o

bool L i s t a : : CodaPari ( ) onst {


PRe p = getPuntCoda ( ) ; // r e s t i t u i s e i l punt .
if ( p )
return ( ( p>e l % 2) == 0 ) ;
else
return false ; // r i t o r n a f a l s e per d e f a u l t ;

void

stampa_menu( ) {
out << " 1 : I n s e r i s i . \ n" ;
out << " 2 : Svuota . \ n" ;
out << " 3 : Stampa . \ n" ;
out << " 4 : Count . \ n" ;
out << " 5 : SpostaTestaInCoda . \ n" ;
out << " 6 : CodaPari . \ n" ;
out << " 7 : E s i . \ n" ;

void
void

I n s e r i s i ( L i s t a& l ) ;
Svuota ( L i s t a& l ) ;

a l l a oda , s e ' .

SL. Soluzioni degli eser izi su liste

void Stampa ( L i s t a& l ) ;


void Count ( L i s t a& l ) ;
void SpostaTestaInCoda ( L i s t a&
void CodaPari ( L i s t a& l ) ;
int main ( )
{

l );

Lista l ;

int s e l t a ;
do {

stampa_menu ( ) ;
i n >> s e l t a ;
( s elta ) {
1:
Inseris i ( l );
;
2:
Svuota ( l ) ;
;
3:
Stampa ( l ) ;
;
4:
Count ( l ) ;
;
5:
SpostaTestaInCoda ( l ) ;
;
6:
CodaPari ( l ) ;
;
7:
;
:
out << " S e l t a non v a l i d a . \ n" ;
;
}
}
( s e l t a != 7 ) ;

swit h
ase
break
ase
break
ase
break
ase
break
ase
break
ase
break
ase
break
default
break
while
return 0 ;

void
}

I n s e r i s i ( L i s t a& l ) {
TElem e l ;
out << " I n s e r i s i v a l o r e elemento : " ;
i n >> e l ;
l . Inseris i ( el );

void
}

Svuota ( L i s t a& l ) {
l . Svuota ( ) ;
out << " L i s t a s v u o t a t a . \ n" ;

void
}

Stampa ( L i s t a& l ) {
out << " I l o n t e n u t o d e l l a l i s t a e ' : " ;
l . Stampa ( ) ;
out << e n d l ;

void

Count ( L i s t a& l ) {

55

SL. Soluzioni degli eser izi su liste

56

out << "N. Elem : " << l . Count ( ) << e n d l ;

void SpostaTestaInCoda ( L i s t a& l ) {


if ( l . SpostaTestaInCoda ( ) )
out << " Elemento s p o s t a t o . \ n" ;
else

out << " I m p o s s i b i l e s p o s t a r e . \ n" ;

void CodaPari ( L i s t a& l )


if ( l . CodaPari ( ) )
out << "L ' elemento
else

{
i n oda e ' p a r i . \ n" ;

out << "L ' elemento i n oda non e ' p a r i . \ n" ;

SL.4 Min e Max


Tra ia a pag. 13

void
if

L i s t a : : MinMax( TElem& min , TElem& max)


( first ) {
min = f i r s t >e l ;
max = f i r s t >e l ;
PRe p = f i r s t >s u ;

onst

while ( p ) {
if ( p>e l < min )
min = p>e l ;
if ( p>e l > max)
}

max = p>e l ;
p = p>s u ;

SL.5 ListaStati a
Tra ia a pag. 14

#in lude <i o s t r e a m>


using namespa e s t d ;
onst int NMAX = 1 0 0 ;
typedef int TElem ;
lass L i s t a {
private :
TElem v [NMAX ;
int nelem ;
publi :
Lista ( ) ;

SL. Soluzioni degli eser izi su liste


~Lista ( ) ;

};

void I n s e r i s i I n C o d a ( TElem
void Svuota ( ) ;
void Stampa ( ) onst ;
int Count ( ) onst ;

el );

L i s t a : : L i s t a ( ) : nelem ( 0 ) {
}
Lista ::~ Lista () {
// Qui non n e e s s a r i a al una o p e r a z i o n e
// I l d i s t r u t t o r e p o t e v a an he e s s e r e omesso d e l t u t t o .
}

void
if
}

L i s t a : : I n s e r i s i I n C o d a ( TElem e l ) {
( nelem < NMAX) {
v [ nelem = e l ;
nelem++;

void
}

L i s t a : : Svuota ( ) {
nelem = 0 ;

void L i s t a : : Stampa ( ) onst {


for ( int i = 0 ; i < nelem ;
}

out << v [ i << " " ;


out << e n d l ;

int L i s t a : : Count ( ) onst


return nelem ;

i ++)

void

stampa_menu( ) {
out << " 1 : I n s e r i s i I n C o d a . \ n" ;
out << " 2 : Svuota . \ n" ;
out << " 3 : Stampa . \ n" ;
out << " 4 : Count . \ n" ;
out << " 5 : E s i . \ n" ;

void I n s e r i s i I n C o d a ( L i s t a&
void Svuota ( L i s t a& l ) ;
void Stampa ( L i s t a& l ) ;
void Count ( L i s t a& l ) ;
int main ( )
{

Lista l ;

int s e l t a ;
do {

stampa_menu ( ) ;
i n >> s e l t a ;
( s elta ) {
1:
Inseris iInCoda ( l ) ;
;

swit h
ase
break

l );

57

SL. Soluzioni degli eser izi su liste

ase 2 :
Svuota ( l ) ;
break ;
ase 3 :
Stampa ( l ) ;
break ;
ase 4 :
Count ( l ) ;
break ;
ase 5 :
break ;
default :
out << " S e l t a non
break ;
}
} while ( s e l t a != 5 ) ;
return 0 ;

58

v a l i d a . \ n" ;

void
}

I n s e r i s i I n C o d a ( L i s t a& l ) {
TElem e l ;
out << " I n s e r i s i v a l o r e elemento : " ;
i n >> e l ;
l . Inseris iInCoda ( el ) ;

void
}

Svuota ( L i s t a& l ) {
l . Svuota ( ) ;
out << " L i s t a s v u o t a t a . \ n" ;

void
}

Stampa ( L i s t a& l ) {
out << " I l o n t e n u t o d e l l a l i s t a e ' : " ;
l . Stampa ( ) ;
out << e n d l ;

void
}

Count ( L i s t a& l ) {
out << "N. Elem : " << l . Count ( ) << e n d l ;

SL.6 Ordinata
Tra ia a pag. 14

bool L i s t a : : EOrdinata ( ) onst {


int i = 0 ;
while ( i < nelem 1) {
if ( v [ i > v [ i +1)
return false ; // e s e s u b i t o
}
}

i ++;

return true ;

s e t r o v a un ' i n v e r s i o n e

// e s e per non aver t r o v a t o al una i n v e r s i o n e

SL. Soluzioni degli eser izi su liste

59

nelem = 5

nelem = 8

Figura SL.2: Eliminazione degli elementi on valore 0 dal vettore

SL.7 Elimina Tutti


Tra ia a pag. 15

Ipotizzando he l'elemento da eliminare sia 0, il metodo

EliminaTutti()

modi a il vettore degli elementi ome mostrato in Figura SL.2


Per realizzare l'eliminazione si utilizzano due indi i

nelem-1,

j:

va da 0 a

memorizza il riempimento orrente del vettore ripulito.

s andendo tutti gli elementi progressivamente;

Si noti ome non sia ne essario utilizzare un vettore di supporto, ma tutto


il pro edimento possa essere svolto su un uni o vettore. Di seguito si riporta
il odi e del metodo

EliminaTutti().

int L i s t a : : E l i m i n a T u t t i ( onst TElem& e l ) {


int j = 0 ;
int ount = 0 ;
for ( int i = 0 ; i < nelem ; i ++) {
if ( v [ i == e l ) // elemento t r o v a t o
ount++; // in remento i l o n t a t o r e e
else {
if ( i != j ) // i e j sono d i v e r s i ? (
}

non r i o p i o l ' elemento

i n u t i l e r i o p i a r e s e i == j )
v [ j = v [ i ; // l o r i o p i o n e l v e t t o r e r i p u l i t o
j ++; // i l v e t t o r e r i p u l i t o ha ora un elemento i n p i

nelem = nelem ount ;


ount ;

return

SL.8 Somma Coda


Tra ia a pag. 15

L'appro io in generale pi e iente per risolvere questo problema onsiste

SL. Soluzioni degli eser izi su liste

60

nel memorizzare in un membro privato della lista il valore della oda. Tale valore deve essere ostantemente aggiornato, a ura di tutti i metodi he
possono potenzialmente alterarlo: inserimento, eliminazione, svuotamento. . .

SommaCoda() nis e per alterare il valore delmostrano le implementazioni dei metodi Inseris i()

e . Si noti he lo stesso metodo


la oda. Di seguito si
e

SommaCoda(),

nelle ipotesi he la lista sia dotata di una variabile-membro

privata denita ome segue:

lass Lista {
private:
...
TElem valoreCoda;
...
};

void

L i s t a : : I n s e r i s i ( TElem e l ) {
// I n s e r i m e n t o i n t e s t a
PRe p =
Re ord ;
p>e l = e l ;
p>s u = f i r s t ;
first = p;
nelem++;

new

// Grazie a l l a prossima i s t r u z i o n e , l a v a r i a b i l e membro valoreCoda


// o n t e r r sempre i l v a l o r e d e l l ' elemento d i oda .
( ! f i r s t >s u )
valoreCoda = e l ;

if

void
if

L i s t a : : SommaCoda ( ) {
( first ) {
// Se l a l i s t a non vuota , l a v a r i a b i l e membro o n t i e n e un v a l o r e o r r e t t o .
//Lo sommo a t u t t i g l i e l e m e n t i .
PRe p = f i r s t ;
(p) {
p>e l = p>e l + valoreCoda ;
p = p>s u ;
}

while

// In q u e s t o punto , i l v a l o r e d e l l ' elemento d i oda r a d d o p p i a t o .


// Aggiorno l a v a r i a b i l e membro .
valoreCoda = valoreCoda 2 ;

SL.9 Sposta Testa in Coda


Tra ia a pag. 15

Per svolgere l'operazione si fa uso di un metodo di supporto

getPuntCoda()

SL. Soluzioni degli eser izi su liste

61

deputato a restituire il puntatore all'elemento di oda della lista, se esistemte.

Si noti he nessun elemento viene reato (new) o distrutto (delete), ma

l'operazione eettuata es lusivamente mediante ri ollo azione di puntatori.

// Metodo p r i v a t o

onst

PRe L i s t a : : getPuntCoda ( )
{
// R e s t i t u i s e i l p u n t a t o r e a l l a oda d e l l a l i s t a
( f i r s t ) { // non e s i s t e una oda s e l a l i s t a vuota ;
PRe p = f i r s t ;
( p>s u )
p = p>s u ;

if

while

return
else
return

}
}

p;
0;

// Metodo p u b b l i o

bool L i s t a : : SpostaTestaInCoda ( ) {
PRe p = getPuntCoda ( ) ; // r e s t i t u i s e
if ( p ) {
}
}

i l punt . a l l a oda , s e ' .

p>s u = f i r s t ;
f i r s t = f i r s t >s u ;
p>su >s u = 0 ;

return

( p != 0 ) ; // s e p non 0 , l o spostamento s t a t o e f f e t t u a t o

SL.10 Elimina Pari e Dispari


Tra ia a pag. 15

unsigned int
int n = 0 ;
if ( f i r s t )

Lista : : EliminaElementiPostoDispari () {

{
PRe p = f i r s t ; // p punta a l primo elemento ( d i i n d i e 0 , q u i n d i p a r i )

// Se p punta ad un elemento , e q u e s t o elemento ha un s u e s s i v o . . .


( p && p>s u ) {
PRe tbd = p>s u ; // . . . i l s u e s s i v o deve e s s e r e e l i m i n a t o .
p>s u = p>su >s u ; // S o l l e g o l ' elemento da a n e l l a r e d a l l a atena ,
tbd ; // l o d i s t r u g g o ,
// p passa a l l ' elemento s u e s s i v o , sempre d i i n d i e p a r i ( n e l l a l i s t a o r i g i n a l e ) .
p = p>s u ;
n++;
}

while

delete

}
}

return

n;

unsigned int

Lista : : EliminaElementiPostoPari () {

SL. Soluzioni degli eser izi su liste

62

int n = 0 ;
if ( f i r s t )

{ // e s i s u b i t o s e l a l i s t a vuota . . .
// . . . a l t r i m e n t i a n e l l a s u b i t o i l primo elemento ( i n d i e 0)
PRe tbd = f i r s t ;
f i r s t = f i r s t >s u ;
tbd ;
n++;

delete

}
}

// p o i h f i r s t s t a t o s p o s t a t o i n a v a n t i d i un elemento non mi r e s t a he
// e l i m i n a r e t u t t i g l i e l e m e n t i d i p o s t o d i s p a r i d e l l ' a t t u a l e l i s t a .
n = n + EliminaElementiPostoDispari ( ) ;

return

n;

SL.11 Lista Doppiamente Collegata


Tra ia a pag. 16

#in lude <i o s t r e a m>


using namespa e s t d ;
stru t Re ord ;
typedef Re ord PRe ;
typedef int TElem ;
stru t Re ord {
};

TElem e l ;
PRe p r e ;
PRe s u ;

lass L i s t a
private :

PRe f i r s t ;
PRe l a s t ;

unsigned int nelem ;


L i s t a ( onst L i s t a &); // i n i b i s e l a o p i a mediante o s t r u t t o r e
void operator= ( onst L i s t a &); // i n i b i s e l ' a s s e g n a z i o n e
publi :
Lista ( ) ;
~Lista ( ) ;

};

void I n s e r i s i ( TElem e l ) ;
void Svuota ( ) ;
void StampaDiretta ( ) onst ;
void StampaInversa ( ) onst ;
void StampaAlternata ( ) onst ;
unsigned int Count ( ) onst ;

L i s t a : : L i s t a ( ) : f i r s t ( 0 ) , l a s t ( 0 ) , nelem ( 0 ) {
}
Lista ::~ Lista () {

SL. Soluzioni degli eser izi su liste

63

Svuota ( ) ;

void

L i s t a : : I n s e r i s i ( TElem e l ) {
// I n s e r i m e n t o i n oda
PRe p =
Re ord ;
p>e l = e l ;
p>s u = 0 ;
p>p r e = l a s t ;
( last )
l a s t >s u = p ;
last = p;

new

if

if
}

(! first )
first = p;

nelem++;

void L i s t a : : Svuota ( ) {
PRe tbd ; // t o be d e l e t e d
while ( f i r s t != 0) {
tbd = f i r s t ;
f i r s t = f i r s t >s u ;
tbd ;

delete

}
nelem = 0 ;
last = 0;

void L i s t a : : StampaDiretta ( ) onst


PRe p = f i r s t ;
while ( p != 0) {
}

out << p>e l << " " ;


p = p>s u ;

void L i s t a : : StampaInversa ( ) onst


PRe p = l a s t ;
while ( p != 0) {
}

out << p>e l << " " ;


p = p>p r e ;

void

L i s t a : : StampaAlternata ( )
PRe p = f i r s t ;
PRe q = l a s t ;
done =
;

bool
false
while ( ( p ) && ! done )
out << p>e l << "
if ( q != p )

onst

{
";

out << q>e l << " " ;

// s e p e q sono s o v r a p p o s t i oppure sono o n s e u t i v i


// abbiamo t e r m i n a t o
( ( p == q ) | | ( p>s u == q ) )
done =
;

if

true

p = p>s u ;

SL. Soluzioni degli eser izi su liste

64

q = q>p r e ;

unsigned int L i s t a : : Count ( ) onst


return nelem ;

void

stampa_menu( ) {
out << " 1 : I n s e r i s i . \ n" ;
out << " 2 : Svuota . \ n" ;
out << " 3 : Stampa D i r e t t a . \ n" ;
out << " 4 : Stampa I n v e r s a . \ n" ;
out << " 5 : Stampa A l t e r n a t a . \ n" ;
out << " 6 : Count . \ n" ;
out << " 7 : E s i . \ n" ;

void I n s e r i s i ( L i s t a& l ) ;
void Svuota ( L i s t a& l ) ;
void StampaDiretta ( L i s t a& l ) ;
void StampaInversa ( L i s t a& l ) ;
void StampaAlternata ( L i s t a& l ) ;
void Count ( L i s t a& l ) ;
int main ( )
{

Lista l ;

int s e l t a ;
do {

stampa_menu ( ) ;
i n >> s e l t a ;
( s elta ) {
1:
Inseris i ( l );
;
2:
Svuota ( l ) ;
;
3:
StampaDiretta ( l ) ;
;
4:
StampaInversa ( l ) ;
;
5:
StampaAlternata ( l ) ;
;
6:
Count ( l ) ;
;
7:
;
:
out << " S e l t a non v a l i d a . \ n" ;
;
}
}
( s e l t a != 7 ) ;

swit h
ase
break
ase
break
ase
break
ase
break
ase
break
ase
break
ase
break
default
break
while
return 0 ;

SL. Soluzioni degli eser izi su liste

65

void
}

I n s e r i s i ( L i s t a& l ) {
TElem e l ;
out << " I n s e r i s i v a l o r e elemento : " ;
i n >> e l ;
l . Inseris i ( el );

void
}

Svuota ( L i s t a& l ) {
l . Svuota ( ) ;
out << " L i s t a s v u o t a t a . \ n" ;

void
}

StampaDiretta ( L i s t a& l ) {
out << "Stampa D i r e t t a : " ;
l . StampaDiretta ( ) ;
out << e n d l ;

void
}

StampaInversa ( L i s t a& l ) {
out << "Stampa I n v e r s a : " ;
l . StampaInversa ( ) ;
out << e n d l ;

void
}

StampaAlternata ( L i s t a& l ) {
out << "Stampa A l t e r n a t a : " ;
l . StampaAlternata ( ) ;
out << e n d l ;

void
}

Count ( L i s t a& l ) {
out << " I l numero d i e l e m e n t i o n t e n u t i n e l l a l i s t a e ' : " <<
l . Count ( ) << e n d l ;

SL.12 Ribalta
Tra ia a pag. 17

L'appro io in generale pi e iente per ribaltare la lista onsiste nel modi are la ongurazione di tutti i puntatori ontenuti nella struttura, senza
pertanto eettuare spostamenti si i di elementi.

Di seguito si fornis ono

due soluzioni, la prima basata su un metodo iterativo, la se onda su uno


ri orsivo.

Appro io iterativo
Si onsideri la Figura SL.3(a), in ui riportata la lista di partenza.

Per

ottenerne il ribaltamento su iente he il primo elemento ( he punta ad

el2 )

passi a puntare a 0, he il se ondo elemento ( he punta ad

puntare al primo, he il terzo elemento ( he punta ad


al se ondo. . . e os via. Inne, il puntatore

first

el4 )

el3 )

passi a

passi a puntare

( he punta ad

el1 )

dovr

SL. Soluzioni degli eser izi su liste

first

el1

66

el2

eln

(a) Lista originale

eli-1

eli

p1

p2

eli+1

(b) Prima dell'i-esima iterazione

eli-1

eli

eli+1

p1

p2

temp

( ) Dopo l'i-esima iterazione

first

el1

el2

eln

(d) Lista ribaltata

Figura SL.3: Il pro esso logi o di ribaltamento di una lista

SL. Soluzioni degli eser izi su liste


puntare all'elemento

eln .

67

Questo pro edimento pu essere svolto servendosi

di due puntatori he iniziano a s orrere la lista nell'uni a direzione on essa,


puntando di volta in volta a due elementi onse utivi e spostandosi in avanti
di un elemento alla volta. Ad ogni passo dell'iterazione lo s ambio pu essere
eettuato servendosi di un terzo puntatore temporaneo (vedi Figure SL.3(b)
e SL.3( )). Lo stato nale della lista al termine dell'iterazione riportato in
Figura SL.3(d).

// Versione i t e r a t i v a d e l metodo R i b a l t a ( )
// Metodo P u b b l i o
Lista : : Ribalta () {
( f i r s t && f i r s t >s u ) { // s e l a l i s t a o n t i e n e almeno 2 e l e m e n t i
PRe p1 = f i r s t ; // memorizzo i n p1 i l primo
PRe p2 = p1>s u ; // memorizzo i n p2 i l se ondo
p1>s u = 0 ; // p1 , d i v e n t a n d o l ' u l t i m o elemento , deve puntare a z e r o

void
if

while

( p2>s u ) { // s e p2 non l ' u l t i m o elemento


PRe temp = p2>s u ; // memorizzo i n temp i l s u e s s i v o d i p2
p2>s u = p1 ; // i l s u e s s i v o d i p2 ora p1

p1 = p2 ; // p1 d i v e n t a p2 ;
p2 = temp ; // p2 d i v e n t a temp

// i n q u e s t o punto d e l o d i e p1 e p2 puntano a g l i u l t i m i
// due e l e m e n t i d e l l a l i s t a .
p2>s u = p1 ; // i l s u e s s i v o d i p2 ora p1
f i r s t = p2 ; // p2 ora l a nuova t e s t a

Appro io ri orsivo
Il ribaltamento della lista pu essere appro iato ome un problema ri orsivo.
Infatti, avendo una lista, la sua versione ribaltata si ottiene isolando il primo
elemento, ribaltando la restante parte della lista, e posponendo a questa
l'elemento isolato.

Il problema del ribaltamento di una lista si ri ondu e

dunque al ribaltamento di una se onda lista ostituita da un elemento in


meno. Di questo passo i si trover a ribaltare una lista ostituita da un uni o
elemento, la ui versione ribaltata uguale a s stessa. Durante il pro esso
di ribaltamento bisogna an he prestare attenzione a redirigere orrettamente
la testa della (sotto)lista di volta in volta onsiderata.

// Versione r i o r s i v a d e l metodo R i b a l t a ( )
// Metodo p r i v a t o
PRe L i s t a : : _ r i b a l t a ( PRe p ) {
( ( ! p ) | | ( ! p>s u ) ) // s e l a l i s t a formata da 0 o 1 e l e m e n t i non f a i o n i e n t e
p;

if

return

SL. Soluzioni degli eser izi su liste

else

{
// memorizzo i n v e h i a _ t e s t a l a v e h i a t e s t a
PRe v e h i a _ t e s t a = p ;
// memorizzo i n ve hio_se ondo i l v e h i o se ondo elemento
PRe ve hio_se ondo = p>s u ;
// r i b a l t o l a s o t t o l i s t a on t e s t a i n ve hio_se ondo . . .
// . . . e memorizzo i n nuova_testa l a nuova t e s t a .
PRe nuova_testa = _ r i b a l t a ( ve hio_se ondo ) ;

// l a v e h i a t e s t a d i v i e n e l ' u l t i m o elemento ( e q u i n d i punta a 0)


v e h i a _ t e s t a >s u = 0 ;
// i l v e h i o se ondo elemento punta a l l a v e h i a t e s t a
ve hio_se ondo >s u = v e h i a _ t e s t a ;

return

nuova_testa ; // r e s t i t u i s o l a nuova t e s t a

// Metodo p u b b l i o
Lista : : Ribalta () {
f i r s t = _ribalta ( f i r s t ) ;
}

void

68

Capitolo SA
Soluzioni degli eser izi su alberi
binari
SA.1 Albero Binario
Tra ia a pag. 18

File AlberoBinario.h

#ifndef
#define
/

_ALBEROBINARIO_H_
_ALBEROBINARIO_H_

C l a s s e Albero Binario .
La l a s s e implementa i metodi d i a g g i u n t a , e l i m i n a z i o n e e r i e r a d i un
elemento . I n o l t r e p e r m e t t e l a v i s i t a i n ordine , p r e o r d i n e e p o s t o r d i n e . E '
i n f i n e implementato i l o s t r u t t o r e d i o p i a .
L ' implementazione d i t u t t i i metodi b a s a t a su a p p o s i t i metodi r i o r s i v i .

stru t Nodo ; // Forward d e l a r a t i o n


typedef Nodo PNodo ;
typedef int TElem ; //L ' a l b e r o o n t i e n e
lass A l b e r o B i n a r i o {
private :

interi

PNodo r o o t ; // r a d i e d e l l ' a l b e r o

// Metodi r i o r s i v i d i s u p p o r t o
_CopiaAlbero ( PNodo& dest ,
PNodo& s o u r e ) ;
_Svuota (
PNodo& n ) ;
_AggiungiElem ( PNodo& n ,
TElem& e l ) ;
_ S o s t i t u i s e ( PNodo& n , PNodo& p ) ;
_InAlb (
PNodo& n ,
TElem& e l )
;
_Elimina ( PNodo& n ,
TElem& e l ) ;
_PreOrdine (
PNodo& n )
;
_PostOrdine (
PNodo& n )
;

void
void
void
void
bool
void
void
void

onst
onst
onst
onst
onst
onst
onst
onst
onst
onst

69

onst

SA. Soluzioni degli eser izi su alberi binari

70

void _InOrdine ( onst PNodo& n ) onst ;


publi :
A l b e r o B i n a r i o ( ) ; // o s t r u t t o r e senza parametri
A l b e r o B i n a r i o ( onst A l b e r o B i n a r i o & a ) ; // o s t r u t t o r e
~ A l b e r o B i n a r i o ( ) ; // D i s t r u t t o r e

};

void
bool
void
void
void
void
void

#endif

onst
onst
onst
onst
onst
onst

di opia

AggiungiElem (
TElem& e l ) ;
InAlb (
TElem& e l )
;
Elimina (
TElem& e l ) ;
Svuota ( ) ;
PreOrdine ( )
;
PostOrdine ( )
;
InOrdine ( )
;

onst

/ _ALBEROBINARIO_H_ /

File AlberoBinario. pp

#in lude <i o s t r e a m . h>


#in lude " A l b e r o B i n a r i o . h"
stru t Nodo { // S t r u t t u r a Nodo
};

TElem e l ;
PNodo s i n ;
PNodo des ;

AlberoBinario : : AlberoBinario ( ) : root (0) {


}

onst

AlberoBinario : : AlberoBinario (
AlberoBinario& a ) {
(
!= &a ) // o p i a s o l o da un o g g e t t o d i f f e r e n t e
_CopiaAlbero ( root , a . r o o t ) ;
}

if this

AlberoBinario : :~ AlberoBinario () {
Svuota ( ) ;
}

// Metodi p r i v a t i r i o r s i v i d i s u p p o r t o

void

onst

A l b e r o B i n a r i o : : _CopiaAlbero ( PNodo& dest ,


PNodo& s o u r e ) {
// Questo metodo r i o r s i v o a e t t a i n i n g r e s s o un p u n t a t o r e ad un a l b e r o
// s o r g e n t e ( s o u r e ) e r e s t i t u i s e i n u s i t a un p u n t a t o r e ad un a l b e r o he
// v i e n e o s t r u i t o d a l l a o p i a d e l primo .
( s o u r e ) { // s e l a s o r g e n t e non l ' a l b e r o vuoto
dest =
Nodo ; // rea un nuovo nodo
dest >e l = s o u r e >e l ; // assegna i l o n t e n u t o d a l l a s o r g e n t e a l l a d e s t i n a z i o n e

if

new

//Ora b i s o g n a r i r e a r e i l s o t t o a l b e r o s i n i s t r o ed i l s o t t o a l b e r o d e s t r o
// d e l nodo p u n t a t o da d e s t r i o p i a n d o i r i s p e t t i v i s o t t o a l b e r i p u n t a t i da
// s o u r e . R i f l e t t e n d o i , l ' o p e r a z i o n e d e s i d e r a t a d e l t u t t o analoga a q u e l l a
// g i i n v o a t a a p a r t i r e d a l l a r a d i e . E ' q u i n d i p o s s i b i l e s f r u t t a r e l a
// r i o r s i o n e ed i n v o a r e l o s t e s s o " s e r v i z i o " _CopiaAlbero ( ) o n s i d e r a n d o
// sour e >des e sour e >s i n ome r a d i i d i due d i s t i n t i a l b e r i .

_CopiaAlbero ( dest >s i n , s o u r e >s i n ) ; // assegna i l s o t t o a l b e r o s i n i s t r o


_CopiaAlbero ( dest >des , s o u r e >des ) ; // assegna i l s o t t o a l b e r o d e s t r o

else

dest = 0;

SA. Soluzioni degli eser izi su alberi binari

71

void
if
}

new

else
if ( e l > n>e l )
_AggiungiElem ( n>des ,
else

el );

_AggiungiElem ( n>s i n , e l ) ;

bool
if
if

onst

A l b e r o B i n a r i o : : _AggiungiElem ( PNodo& n ,
TElem& e l ) {
( ! n) {
n =
Nodo ; // s i rea un nuovo elemento d e l l ' a l b e r o . . .
n>e l = e l ; // . . . e l o s i i n i z i a l i z z a .
n>s i n = 0 ;
n>des = 0 ;

A l b e r o B i n a r i o : : _InAlb (
( ! n)
;

return false

onst

PNodo& n ,

onst

TElem& e l )

onst

( n>e l == e l ) // l ' elemento e r a t o n e l l a r a d i e

return true ;

if ( e l > n>e l ) // maggiore


return _InAlb ( n>des , e l ) ;
else
return _InAlb ( n>s i n , e l ) ;

del ontenuto d e l l a radi e ?


// e r a n e l s o t t o a l b e r o d e s t r o
// e r a n e l s o t t o a l b e r o s i n i s t r o

void
//
//
//
//
//
//
//

A l b e r o B i n a r i o : : _ S o s t i t u i s e ( PNodo& n , PNodo& p ) {
Questo metodo ha ome parametri d i i n g r e s s o u s i t a :
n : un p u n t a t o r e a l l a r a d i e d i un a l b e r o ;
p : un p u n t a t o r e ad un nodo .
I l suo e f f e t t o q u e l l o d i s o s t i t u i r e i l nodo p u n t a t o da p on i l massimo
elemento d e l l ' a l b e r o n . La prima v o l t a q u e s t o metodo v i e n e i n v o a t o ( n e l metodo
e l i m i n a ) on l a s i n t a s s i _ S o s t i s u i s i ( n>sin , n ) , p e r u i s i p r o v v e d e a l l a
s o s t i t u z i o n e d e l nodo n on i l massimo d e l suo s o t t o a l b e r o s i n i s t r o .
PNodo q ;
( ! n>des ) {
q = n;
n = n>s i n ;
q>s i n=p>s i n ;
q>des=p>des ;
p=q ;
}
_ S o s t i t u i s e ( n>des , p ) ;

if

else

void
if

onst

A l b e r o B i n a r i o : : _Elimina ( PNodo& n ,
TElem& e l ) {
( n ) { // Eliminare da un a l b e r o vuoto non produ e al una o p e r a z i o n e
( n>e l == e l ) {
// a n e l l a nodo o r r e n t e
PNodo p = n ;
( ! n>s i n ) // i l ramo s i n i s t r o d e l nodo da e l i m i n a r e vuoto ?
n = n>des ; // s o s t i t u z i o n e d e l nodo o l suo s o t t o a l b e r o d e s t r o

if

if
else
if ( ! n>des ) // i l ramo d e s t r o d e l nodo da e l i m i n a r e vuoto ?
n = n>s i n ; // s o s t i t u z i o n e d e l nodo o l suo s o t t o a l b e r o s i n i s t r o
else // i l nodo da e l i m i n a r e ha s i a i l s o t t o a l b e r o s x he q u e l l o dx
_ S o s t i t u i s e ( n>s i n , n ) ; // hiamo i l " s e r v i z i o " S o s t i t u i s e ( )
delete p ;
else

SA. Soluzioni degli eser izi su alberi binari

if ( e l < n>e l )
_Elimina ( n>s i n ,
else
}

void
if
}

void
if
}

void
if
}

void
if
}

72

el );

_Elimina ( n>des , e l ) ;

onst

A l b e r o B i n a r i o : : _Svuota (
PNodo& n ) {
( n ) { // Agis e s o l o s e l ' a l b e r o e s i s t e
_Svuota ( n>s i n ) ;
_Svuota ( n>des ) ;
n;

delete

A l b e r o B i n a r i o : : _PreOrdine (
(n) {
out << n>e l << " " ;
_PreOrdine ( n>s i n ) ;
_PreOrdine ( n>des ) ;

onst

A l b e r o B i n a r i o : : _PostOrdine (
(n) {
_PostOrdine ( n>s i n ) ;
_PostOrdine ( n>des ) ;
out << n>e l << " " ;

A l b e r o B i n a r i o : : _InOrdine (
(n) {
_InOrdine ( n>s i n ) ;
out << n>e l << " " ;
_InOrdine ( n>des ) ;

onst

onst

onst

PNodo& n )

PNodo& n )

PNodo& n )

onst

onst

// Metodi p u b b l i i

void
}

A l b e r o B i n a r i o : : AggiungiElem (
_AggiungiElem ( root , e l ) ;

bool A l b e r o B i n a r i o : : InAlb ( onst


return _InAlb ( root , e l ) ;

onst

TElem& e l ) {

TElem& e l )

onst

void
}

A l b e r o B i n a r i o : : Elimina (
_Elimina ( root , e l ) ;

onst

TElem& e l ) {

void
}

A l b e r o B i n a r i o : : Svuota ( ) {
_Svuota ( r o o t ) ;
root = 0;

void
}

A l b e r o B i n a r i o : : PreOrdine ( )
_PreOrdine ( r o o t ) ;

onst

SA. Soluzioni degli eser izi su alberi binari

void
}

A l b e r o B i n a r i o : : PostOrdine ( )
_PostOrdine ( r o o t ) ;

void
}

A l b e r o B i n a r i o : : InOrdine ( )
_InOrdine ( r o o t ) ;

onst

onst

73

File main. pp

#in lude
#in lude

<i o s t r e a m . h>
" A l b e r o B i n a r i o . h"

// P r o t o t i p i d i f u n z i o n i d i s u p p o r t o per l a v e r i f i a d e l o r r e t t o funzionamento
// d e i metodi d e l l a l a s s e A l b e r o B i n a r i o .
stampaMenu ( ) ;
I n s e r i s i ( AlberoBinario& a ) ;
Ri er a ( AlberoBinario& a ) ;
Elimina ( A l b e r o B i n a r i o & a ) ;
Svuota ( A l b e r o B i n a r i o & a ) ;
PreOrdine ( A l b e r o B i n a r i o & a ) ;
InOrdine ( A l b e r o B i n a r i o & a ) ;
PostOrdine ( A l b e r o B i n a r i o & a ) ;
Copia ( A l b e r o B i n a r i o & a ) ;

void
void
void
void
void
void
void
void
void
int main ( )
har ;

AlberoBinario albero ;

do

{
stampaMenu ( ) ;
i n >> ;
in . ignore ( ) ;

swit h ( ) {
ase ' 1 ' :
I n s e r i s i ( albero ) ;
break ;
ase ' 2 ' :
Ri er a ( albero ) ;
break ;
ase ' 3 ' :
Elimina ( a l b e r o ) ;
break ;
ase ' 4 ' :
Svuota ( a l b e r o ) ;
break ;
ase ' 5 ' :
PreOrdine ( a l b e r o ) ;
break ;
ase ' 6 ' :
InOrdine ( a l b e r o ) ;
break ;
ase ' 7 ' :
PostOrdine ( a l b e r o ) ;
break ;
ase ' 8 ' :
Copia ( a l b e r o ) ;
break ;
ase ' 9 ' :
break ;

SA. Soluzioni degli eser izi su alberi binari

default :
out << " S e l t a
break ;
}
} while ( != ' 9 ' ) ;
return 0 ;

non v a l i d a . \ n" ;

void

stampaMenu ( ) {
out << e n d l ;
out << " 1 . I n s e r i s i " << e n d l ;
out << " 2 . R i e r a " << e n d l ;
out << " 3 . Elimina " << e n d l ;
out << " 4 . Svuota " << e n d l ;
out << " 5 . Pre o r d i n e " << e n d l ;
out << " 6 . InOrdine " << e n d l ;
out << " 7 . Post Ordine " << e n d l ;
out << " 8 . Copia a l b e r o " << e n d l ;
out << " 9 . E s i " << e n d l ;
out << e n d l ;
out << " S e l t a : " ;

void I n s e r i s i ( A l b e r o B i n a r i o & a )
int i ;
}

out << " I n s e r i s i i n t e r o : " ;


i n >> i ;
a . AggiungiElem ( i ) ;

void R i e r a ( A l b e r o B i n a r i o & a )
int i ;

out << " I n s e r i s i i n t e r o : " ;


i n >> i ;
( a . InAlb ( i ) )
out << " Trovato . \ n" ;

if
else

out << "Non t r o v a t o . \ n" ;

void Elimina ( A l b e r o B i n a r i o & a )


int i ;
}

out << " I n s e r i s i i n t e r o : " ;


i n >> i ;
a . Elimina ( i ) ;

void
}

Svuota ( A l b e r o B i n a r i o & a ) {
out << " Svuotamento a l b e r o . " << e n d l ;
a . Svuota ( ) ;

void
}

PreOrdine ( A l b e r o B i n a r i o & a ) {
out << "Stampa i n pre o r d i n e : \ n" ;
a . PreOrdine ( ) ;
out << e n d l ;

void

InOrdine ( A l b e r o B i n a r i o & a ) {
out << "Stampa i n o r d i n e : \ n" ;
a . InOrdine ( ) ;

74

SA. Soluzioni degli eser izi su alberi binari

75

out << e n d l ;

void
}

PostOrdine ( A l b e r o B i n a r i o & a ) {
out << "Stampa i n post o r d i n e : \ n" ;
a . PostOrdine ( ) ;
out << e n d l ;

void
}

Copia ( A l b e r o B i n a r i o & a ) {
AlberoBinario b( a ) ;
out << "La v i s i t a i n o r d i n e d e l l ' a l b e r o o p i a t o e ' : " ;
b . InOrdine ( ) ;
out << e n d l ;

SA.2 Numero Elementi


Tra ia a pag. 19

La te ni a pi sempli e per eettuare il onteggio del numero di elementi


ontenuti in un albero, onsiste nel denire un membro privato di tipo intero
non negativo atto a memorizzare tale valore.

Il valore del membro viene

alterato da tutti i metodi della struttura he modi ano il numero di nodi


presenti in essa (inserimento, eliminazione, svuotamento. . . et .).
Qui si mostrer un appro io dierente, di solito meno e iente, onsistente in un metodo ri orsivo he al ola il numero di elementi mediante una
visita ompleta dell'albero.

unsigned int A l b e r o B i n a r i o : : _NumElem( onst


if ( n ) {
unsigned int num = 1 ;

PNodo& n )

onst

num = num + _NumElem( n>s i n ) ;


num = num + _NumElem( n>des ) ;
}
}

return
else
return

num ;
0;

// Metodo p u b b l i o

unsigned int A l b e r o B i n a r i o : : NumElem ( ) onst


return _NumElem( r o o t ) ;

SA.3 O orrenze
Tra ia a pag. 19

// Metodo p r i v a t o

SA. Soluzioni degli eser izi su alberi binari

unsigned int A l b e r o B i n a r i o : : _O orrenze ( onst


int o = 0 ;
if ( n ) {
if ( n>e l == e l )

76

PNodo& n ,

onst

TElem& e l )

onst

o ++;

if

( e l > n>e l ) // i l segno > deve e s s e r e o e r e n t e on l a o n v e n z i o n e


// s t a b i l i t a per l ' i n s e r i m e n t o d e g l i e l e m e n t i n e l l ' a l b e r o
o = o + _O orrenze ( n>des , e l ) ;

else
}
}

o = o + _O orrenze ( n>s i n , e l ) ;

return

o ;

// Metodo p u b b l i o

unsigned int A l b e r o B i n a r i o : : O orrenz e ( onst


return _O orrenze ( root , e l ) ;

TElem& e l )

onst

SA.4 O orrenza Massima


Tra ia a pag. 19

File AlberoBinario.h

#ifndef _ALBEROBINARIO_H_
#define _ALBEROBINARIO_H_
stru t Nodo ;
typedef Nodo PNodo ;
typedef int TElem ;
lass A l b e r o B i n a r i o {
private :
PNodo r o o t ;
int maxo ;
// Metodi r i o r s i v i d i s u p p o r t o
_Svuota (
PNodo& n ) ;
_ I n s e r i s i ( PNodo& n ,
TElem& e l ,
_PreOrdine (
PNodo& n )
;
_PostOrdine (
PNodo& n )
;
_InOrdine (
PNodo& n )
;

void
bool
void
void
void

onst
onst
int urr_o ) ;
onst
onst
onst
onst
onst
onst
A l b e r o B i n a r i o ( onst A l b e r o B i n a r i o &); // i m p e d i s e l a o p i a . . .
A l b e r o B i n a r i o & operator =( onst A l b e r o B i n a r i o &); // . . . e l ' a s s e g n a z i o n e .
publi :
A l b e r o B i n a r i o ( unsigned int max_o ) ;
~AlberoBinario ( ) ;

SA. Soluzioni degli eser izi su alberi binari

};

bool
void
void
void
void

#endif

onst TElem&
onst ;
onst ;
onst ;

Inseris i (
Svuota ( ) ;
PreOrdine ( )
PostOrdine ( )
InOrdine ( )

77

el );

/ _ALBEROBINARIO_H_ /

File AlberoBinario. pp

#in lude <i o s t r e a m>


#in lude " A l b e r o B i n a r i o . h"
using namespa e s t d ;
stru t Nodo { // S t r u t t u r a Nodo
};

TElem e l ;
PNodo s i n ;
PNodo des ;

AlberoBinario : : AlberoBinario (
}

unsigned int

max_o ) : r o o t ( 0 ) , maxo ( max_o ) {

AlberoBinario : :~ AlberoBinario () {
Svuota ( ) ;
}

// Metodi p r i v a t i r i o r s i v i d i s u p p o r t o

bool

onst

int

A l b e r o B i n a r i o : : _ I n s e r i s i ( PNodo& n ,
TElem& e l ,
urr_o ) {
// Questa l a f u n z i o n e r i o r s i v a he s i o upa d e l l ' i n s e r i m e n t o n e l l ' a l b e r o
// d e l l ' elemento s p e i f i a t o i n e l .
//
// Essa s i basa s u l l ' i p o t e s i he , durante l ' i n s e r i m e n t o d i un elemento i n un
// a l b e r o b i n a r i o o r d i n a t o , b i s o g n a n e e s s a r i a m e n t e " p a s s a r e " per g l i e v e n t u a l i
// a l t r i nodi o n t e n e n t i l o s t e s s o v a l o r e . E ' p o s s i b i l e dunque d i s e n d e r e l ' a l b e r o
// i n e r a d e l l a p o s i z i o n e i n u i a g g i u n g e r e l ' elemento e , ontemporaneamente ,
// o n t a r e l ' o o r r e n z a d e l l e e v e n t u a l i r e p l i h e , interrompendo prematuramente
// l ' i n s e r i m e n t o i n aso d i r a g g i u n g i m e n t o d e l numero massimo d i o o r r e n z e .

if

( ! n ) { // s e l ' a l b e r o vuoto i n s e r i s o ertamente


n =
Nodo ;
n>e l = e l ;
n>s i n = 0 ;
n>des = 0 ;
;

new

return true
else {
if ( e l == n>e l ) { // s e l ' elemento o r r e n t e p a r i ad e l . . .
urr_o ++; // . . . in remento urr_o . . .
if ( urr_o >= maxo ) // . . . e s e ha r a g g i u n t o i l l i m i t e . . .
return false ; // . . . e s o on i l v a l o r e f a l s e .

}
// Se sono q u i i l l i m i t e non s t a t o r a g g i u n t o .
( e l > n>e l )
_ I n s e r i s i ( n>des , e l , urr_o ) ;

if
return
else
return

_ I n s e r i s i ( n>s i n , e l , urr_o ) ;

SA. Soluzioni degli eser izi su alberi binari

78

void
if
}

void
if
}

void
if
}

void
if
}

onst

A l b e r o B i n a r i o : : _Svuota (
PNodo& n ) {
( n ) { // Agis e s o l o s e l ' a l b e r o e s i s t e
_Svuota ( n>s i n ) ;
_Svuota ( n>des ) ;
n;

delete

A l b e r o B i n a r i o : : _PreOrdine (
(n) {
out << n>e l << " " ;
_PreOrdine ( n>s i n ) ;
_PreOrdine ( n>des ) ;

onst

A l b e r o B i n a r i o : : _PostOrdine (
(n) {
_PostOrdine ( n>s i n ) ;
_PostOrdine ( n>des ) ;
out << n>e l << " " ;

A l b e r o B i n a r i o : : _InOrdine (
(n) {
_InOrdine ( n>s i n ) ;
out << n>e l << " " ;
_InOrdine ( n>des ) ;

onst

onst

onst

PNodo& n )

PNodo& n )

PNodo& n )

bool A l b e r o B i n a r i o : : I n s e r i s i ( onst
return _ I n s e r i s i ( root , e l , 0 ) ;

TElem& e l ) {

void
}

A l b e r o B i n a r i o : : Svuota ( ) {
_Svuota ( r o o t ) ;
root = 0;

void
}

void
}

A l b e r o B i n a r i o : : PostOrdine ( )
_PostOrdine ( r o o t ) ;

void
}

onst

A l b e r o B i n a r i o : : PreOrdine ( )
_PreOrdine ( r o o t ) ;

A l b e r o B i n a r i o : : InOrdine ( )
_InOrdine ( r o o t ) ;

onst

onst

File main. pp

#in lude
#in lude

<i o s t r e a m>
" A l b e r o B i n a r i o . h"

onst

onst

// Metodi p u b b l i i

SA. Soluzioni degli eser izi su alberi binari

using namespa e

79

std ;

// P r o t o t i p i d i f u n z i o n i d i s u p p o r t o per l a v e r i f i a d e l o r r e t t o funzionamento
// d e i metodi d e l l a l a s s e A l b e r o B i n a r i o .
stampaMenu ( ) ;
I n s e r i s i ( AlberoBinario& a ) ;
Svuota ( A l b e r o B i n a r i o & a ) ;
PreOrdine ( A l b e r o B i n a r i o & a ) ;
InOrdine ( A l b e r o B i n a r i o & a ) ;
PostOrdine ( A l b e r o B i n a r i o & a ) ;

void
void
void
void
void
void
int main ( ) {
har ;
int maxo ;

out << " Quante o o r r e n z e a l massimo per i a s u n elemento ? " ;


i n >> maxo ;
A l b e r o B i n a r i o a l b e r o ( maxo ) ;

do

swit h ( ) {
ase ' 1 ' :
I n s e r i s i ( albero ) ;
break ;
ase ' 2 ' :
Svuota ( a l b e r o ) ;
break ;
ase ' 3 ' :
PreOrdine ( a l b e r o ) ;
break ;
ase ' 4 ' :
InOrdine ( a l b e r o ) ;
break ;
ase ' 5 ' :
PostOrdine ( a l b e r o ) ;
break ;
ase ' 6 ' :
break ;
default :
out << " S e l t a non
break ;
}
} while ( != ' 6 ' ) ;
return 0 ;

void

{
stampaMenu ( ) ;
i n >> ;
in . ignore ( ) ;

v a l i d a . \ n" ;

stampaMenu ( ) {
out << e n d l ;
out << " 1 . I n s e r i s i " << e n d l ;
out << " 2 . Svuota " << e n d l ;
out << " 3 . Pre o r d i n e " << e n d l ;
out << " 4 . InOrdine " << e n d l ;
out << " 5 . Post Ordine " << e n d l ;
out << " 6 . E s i " << e n d l ;
out << e n d l ;
out << " S e l t a : " ;

SA. Soluzioni degli eser izi su alberi binari

void I n s e r i s i ( A l b e r o B i n a r i o & a )
int i ;

80

out << " I n s e r i s i i n t e r o : " ;


i n >> i ;
(a . I n s e r i s i ( i ))
out << " Elemento i n s e r i t o . \ n" ;

if
else

out << " Elemento non i n s e r i t o . \ n" ;

void
}

Svuota ( A l b e r o B i n a r i o & a ) {
out << " Svuotamento a l b e r o . " << e n d l ;
a . Svuota ( ) ;

void
}

PreOrdine ( A l b e r o B i n a r i o & a ) {
out << "Stampa i n pre o r d i n e : \ n" ;
a . PreOrdine ( ) ;
out << e n d l ;

void
}

InOrdine ( A l b e r o B i n a r i o & a ) {
out << "Stampa i n o r d i n e : \ n" ;
a . InOrdine ( ) ;
out << e n d l ;

void
}

PostOrdine ( A l b e r o B i n a r i o & a ) {
out << "Stampa i n post o r d i n e : \ n" ;
a . PostOrdine ( ) ;
out << e n d l ;

SA.5 Profondit Limitata


Tra ia a pag. 20

AlberoBinario : : AlberoBinario (

unsigned int

bool
if

A l b e r o B i n a r i o : : _ I n s e r i s i ( PNodo& n ,

_maxDepth ) : r o o t ( 0 ) ,
maxDepth ( _maxDepth ) {

onst

TElem& e l ,

if

new

return true ;
else
if ( e l > n>e l )
return _ I n s e r i s i ( n>des ,
else
return _ I n s e r i s i ( n>s i n ,

unsigned int

( _maxDepth > 0) {
( ! n) {
n =
Nodo ; // s i rea un nuovo elemento d e l l ' a l b e r o . . .
n>e l = e l ; // . . . e l o s i i n i z i a l i z z a .
n>s i n = 0 ;
n>des = 0 ;

e l , _maxDepth 1 ) ;
e l , _maxDepth 1 ) ;

_maxDepth ) {

SA. Soluzioni degli eser izi su alberi binari

81

return false ;

// Metodo p u b b l i o

bool A l b e r o B i n a r i o : : I n s e r i s i ( onst TElem&


return _ I n s e r i s i ( root , e l , maxDepth ) ;

el ) {

SA.6 Somma
Tra ia a pag. 21

// Metodo p r i v a t o

void
if
}

A l b e r o B i n a r i o : : _Somma(
( n && ( i != 0 ) ) {
n>e l += i ;
_Somma( n>s i n , i ) ;
_Somma( n>des , i ) ;

onst

PNodo& n ,

int

i) {

// Metodo P u b b l i o

void
}

A l b e r o B i n a r i o : : Somma(
_Somma( root , i ) ;

int

i) {

SA.7 Sostituis i
Tra ia a pag. 21

// Metodo p r i v a t o

unsigned int A l b e r o B i n a r i o : : _ S o s t i t u i s i ( PNodo& n , TElem


unsigned int s o s t i t u z i o n i = 0 ;
if ( n ) {
// S o s t i t u i s o prima n e i s o t t o a l b e r i . . .
if ( i > n>e l )
s o s t i t u z i o n i = s o s t i t u z i o n i + _ S o s t i t u i s i ( n>des ,
else

i , TElem j ) {

i , j );

s o s t i t u z i o n i = s o s t i t u z i o n i + _ S o s t i t u i s i ( n>s i n , i , j ) ;

// . . . p o i n e l l a r a d i e
( n>e l == i ) {
n>e l = j ;
s o s t i t u z i o n i ++;
}

if

}
}

return

sostituzioni ;

SA. Soluzioni degli eser izi su alberi binari

82

// Metodo p u b b l i o

unsigned int A l b e r o B i n a r i o : : S o s t i t u i s i ( TElem


return _ S o s t i t u i s i ( root , i , j ) ;

i , TElem j ) {

SA.8 Conta Min e Max


Tra ia a pag. 21

File AlberoBinario.h

#ifndef _ALBEROBINARIO_H_
#define _ALBEROBINARIO_H_
stru t Nodo ; // Forward d e l a r a t i o n
typedef Nodo PNodo ;
typedef unsigned int TElem ; //L ' a l b e r o
lass A l b e r o B i n a r i o {
private :

ontiene i n t er i p o s i t i v i

PNodo r o o t ; // r a d i e d e l l ' a l b e r o

// Metodi r i o r s i v i d i s u p p o r t o

void _ I n s e r i s i ( PNodo& n , onst TElem& e l ) ;


void _Svuota ( onst PNodo& n ) ;
void _PreOrdine ( onst PNodo& n ) onst ;
void _PostOrdine ( onst PNodo& n ) onst ;
void _InOrdine ( onst PNodo& n ) onst ;
unsigned int _ContaMinMax ( onst PNodo& n , TElem Min , TElem Max) onst ;
bool _uguale ( onst PNodo& n1 , onst PNodo& n2 ) onst ;
A l b e r o B i n a r i o ( onst A l b e r o B i n a r i o &); // i m p e d i s e l a o p i a mediante o s t r u t t o r e
void operator=( onst A l b e r o B i n a r i o &); // i m p e d i s e l ' a s s e g n a z i o n e
publi :
A l b e r o B i n a r i o ( ) ; // o s t r u t t o r e senza parametri
~ A l b e r o B i n a r i o ( ) ; // d i s t r u t t o r e

};

void I n s e r i s i ( onst TElem& e l ) ;


void Svuota ( ) ;
unsigned int ContaMinMax ( TElem Min , TElem Max) onst ;
void PreOrdine ( ) onst ;
void PostOrdine ( ) onst ;
void InOrdine ( ) onst ;
bool operator==( onst A l b e r o B i n a r i o & r h s ) onst ;

#endif

/ _ALBEROBINARIO_H_ /

File AlberoBinario. pp

SA. Soluzioni degli eser izi su alberi binari

83

#in lude <i o s t r e a m>


#in lude " A l b e r o B i n a r i o . h"
using namespa e s t d ;
stru t Nodo { // S t r u t t u r a Nodo
};

TElem e l ;
PNodo s i n ;
PNodo des ;

AlberoBinario : : AlberoBinario ( ) : root (0) {


}
AlberoBinario : :~ AlberoBinario () {
Svuota ( ) ;
}

// Metodi p r i v a t i r i o r s i v i d i s u p p o r t o

void
if
}

new

else
if ( e l > n>e l )
_ I n s e r i s i ( n>des ,
else

void
if
}

void
if
}

void
if
}

el );

_ I n s e r i s i ( n>s i n , e l ) ;

onst

A l b e r o B i n a r i o : : _ I n s e r i s i ( PNodo& n ,
TElem& e l ) {
( ! n) {
n =
Nodo ; // s i rea un nuovo elemento d e l l ' a l b e r o . . .
n>e l = e l ; // . . . e l o s i i n i z i a l i z z a .
n>s i n = 0 ;
n>des = 0 ;

void
if

onst

A l b e r o B i n a r i o : : _Svuota (
PNodo& n ) {
( n ) { // Agis e s o l o s e l ' a l b e r o non vuoto
_Svuota ( n>s i n ) ;
_Svuota ( n>des ) ;
n;

delete

A l b e r o B i n a r i o : : _PreOrdine (
(n) {
out << n>e l << " " ;
_PreOrdine ( n>s i n ) ;
_PreOrdine ( n>des ) ;

onst

A l b e r o B i n a r i o : : _PostOrdine (
(n) {
_PostOrdine ( n>s i n ) ;
_PostOrdine ( n>des ) ;
out << n>e l << " " ;

A l b e r o B i n a r i o : : _InOrdine (
(n) {
_InOrdine ( n>s i n ) ;
out << n>e l << " " ;

onst

onst

onst

PNodo& n )

PNodo& n )

PNodo& n )

onst

onst

SA. Soluzioni degli eser izi su alberi binari

84

_InOrdine ( n>des ) ;

unsigned int A l b e r o B i n a r i o : : _ContaMinMax ( onst PNodo& n , TElem


if ( n ) {
int ount = 0 ;
// Se l ' elemento p u n t a t o da e l ompreso t r a Min e Max . . .
if ( ( n>e l >= Min ) && ( n>e l <= Max ) )

Min , TElem Max)

onst

ount ++; // . . . in remento ount .

// Se l ' elemento p u n t a t o da n minore d i Max . . .


( n>e l < Max) {
// . . . a l l o r a n e l s o t t o a l b e r o d e s t r o p o t r e b b e r o e s s e r i a l t r i e l e m e n t i .
ount = ount + _ContaMinMax ( n>des , Min , Max ) ;
}

if

if
}
}

( n>e l >= Min) //E v i e v e r s a per i l s o t t o a l b e r o s i n i s t r o .


ount = ount + _ContaMinMax ( n>s i n , Min , Max ) ;

return
else
return

ount ;
0 ; //L ' a l b e r o vuoto .

bool A l b e r o B i n a r i o : : _uguale ( onst PNodo& n1 , onst PNodo& n2 ) onst {


// Se l e due r a d i i sono 0 ( i o entrambi g l i a l b e r i sono v u o t i ) . . .
if ( ! n1 && ! n2 )
return true ; // . . . i due a l b e r i sono u g u a l i
else
if ( ! n1 | | ! n2 ) // Se una d e l l e due r a d i i 0 . . .
return false ; // . . . i due a l b e r i non sono u g u a l i
// ( p e r h l ' a l t r a ertamente non z e r o )

// Assodato he nessuna d e l l e due r a d i i vuota . . .


( n1>e l != n2>e l ) // . . . s e i due e l e m e n t i p u n t a t i da n1 e n2 sono d i v e r s i . . .
;
// . . . a l l o r a i due a l b e r i non sono u g u a l i .

if

return false

//Dunque , abbiamo due a l b e r i non v u o t i e o n t e n e n t i e l e m e n t i


// d i u g u a l e v a l o r e n e l l a r a d i e .
// Bisogna ora o n t r o l l a r e s e i l o r o s o t t o a l b e r i s i n i s t r o e d e s t r o sono u g u a l i :
// r i o r s i o n e .
_uguale ( n1>s i n , n2>s i n ) && _uguale ( n1>des , n2>des ) ;

return

// Metodi p u b b l i i
AlberoBinario : : I n s e r i s i (
_ I n s e r i s i ( root , e l ) ;
}

void

onst

TElem& e l ) {

void
}

A l b e r o B i n a r i o : : Svuota ( ) {
_Svuota ( r o o t ) ;
root = 0;

unsigned int A l b e r o B i n a r i o : : ContaMinMax ( TElem


return _ContaMinMax ( root , Min , Max ) ;
}

void

A l b e r o B i n a r i o : : PreOrdine ( )
_PreOrdine ( r o o t ) ;

onst

Min , TElem Max)

onst

SA. Soluzioni degli eser izi su alberi binari

85

void
}

A l b e r o B i n a r i o : : PostOrdine ( )
_PostOrdine ( r o o t ) ;

void
}

A l b e r o B i n a r i o : : InOrdine ( )
_InOrdine ( r o o t ) ;

bool
//
//
//
//
//
//

onst

onst

operator onst

onst

AlberoBinario : :
==(
AlberoBinario& rhs )
{
Questo o p e r a t o r e v i e n e i n v o a t o on l a s e g u e n t e s i n t a s s i :
a1 == a2 ;
dove a1 ed a2 sono due i s t a n z e d e l l a l a s s e A l b e r o B i n a r i o .
In q u e s t o aso v i e n e i n v o a t o l ' o p e r a t o r ==() s u l l ' o g g e t t o a1 ,
mentre a2 , parametro a t t u a l e , v i e n e p a s s a t o per r i f e r i m e n t o
prendendo i l p o s t o d e l parametro f o r m a l e r h s .

// Chiamo i l metodo p r i v a t o _uguale ( ) e g l i passo l a mia r a d i e


// e l a r a d i e d e l l ' a l b e r o r h s .
_uguale ( root , r h s . r o o t ) ;

return

File main. pp

#in lude <i o s t r e a m>


#in lude " A l b e r o B i n a r i o . h"
using namespa e s t d ;
// P r o t o t i p i d i f u n z i o n i d i s u p p o r t o per l a v e r i f i a d e l o r r e t t o funzionamento
// d e i metodi d e l l a l a s s e A l b e r o B i n a r i o .
stampaMenu ( ) ;
I n s e r i s i ( AlberoBinario& a ) ;
Svuota ( A l b e r o B i n a r i o & a ) ;
ContaMinMax ( A l b e r o B i n a r i o & a ) ;
PreOrdine ( A l b e r o B i n a r i o & a ) ;
InOrdine ( A l b e r o B i n a r i o & a ) ;
PostOrdine ( A l b e r o B i n a r i o & a ) ;
Uguali ( A l b e r o B i n a r i o & a1 , A l b e r o B i n a r i o & a2 ) ;

void
void
void
void
void
void
void
void
int main ( )

{
// I s t a n z i o due a l b e r i
AlberoBinario albero1 , albero2 ;
// I s t a n z i o un p u n t a t o r e he , i n i z i a l m e n t e , punta a l primo a l b e r o .
A l b e r o B i n a r i o InUso = &a l b e r o 1 ;
;

har
do {
//Comuni o a l l ' u t a n t e q u a l e d e i due a l b e r i s t a u t i l i z z a n d o .
if ( InUso == &a l b e r o 1 )
out << "Ora s t a i l a v o r a n d o s u l l ' a l b e r o 1 . " << e n d l ;
else
out << "Ora s t a i l a v o r a n d o s u l l ' a l b e r o 2 . " << e n d l ;
stampaMenu ( ) ;
i n >> ;
in . ignore ( ) ;

swit h
ase

( ) {
'1 ' :

SA. Soluzioni degli eser izi su alberi binari


I n s e r i s i ( InUso ) ;

break ;
ase ' 2 ' :
Svuota ( InUso ) ;
break ;
ase ' 3 ' :
ContaMinMax ( InUso ) ;
break ;
ase ' 4 ' :
PreOrdine ( InUso ) ;
break ;
ase ' 5 ' :
InOrdine ( InUso ) ;
break ;
ase ' 6 ' :
PostOrdine ( InUso ) ;
break ;
ase ' 7 ' :
Uguali ( a l b e r o 1 , a l b e r o 2 ) ;
break ;
ase ' ' : // passo da un a l b e r o a l l ' a l t r o
if ( InUso == &a l b e r o 1 )
InUso = &a l b e r o 2 ;
else
InUso = &a l b e r o 1 ;
break ;
ase ' 8 ' :
break ;
default :
out << " S e l t a non v a l i d a . \ n" ;
break ;
}
} while ( != ' 8 ' ) ;
return 0 ;

void

stampaMenu ( ) {
out << e n d l ;
out << " 1 . I n s e r i s i " << e n d l ;
out << " 2 . Svuota " << e n d l ;
out << " 3 . ContaMinMax " << e n d l ;
out << " 4 . Pre o r d i n e " << e n d l ;
out << " 5 . InOrdine " << e n d l ;
out << " 6 . Post Ordine " << e n d l ;
out << " 7 . Uguali " << e n d l ;
out << " . Cambia Albero . " << e n d l ;
out << " 8 . E s i " << e n d l ;
out << e n d l ;
out << " S e l t a : " ;

void I n s e r i s i ( A l b e r o B i n a r i o & a )
int i ;
}

out << " I n s e r i s i i n t e r o : " ;


i n >> i ;
a. Inseris i ( i );
out << " Elemento i n s e r i t o . \ n" ;

void

Svuota ( A l b e r o B i n a r i o & a ) {
out << " Svuotamento a l b e r o . " << e n d l ;

86

SA. Soluzioni degli eser izi su alberi binari

87

a . Svuota ( ) ;

void ContaMinMax ( A l b e r o B i n a r i o & a )


int Min , Max ;

out << " I n s e r i s i Min : " ;


i n >> Min ;
out << " I n s e r i s i Max : " ;
i n >> Max ;

out << " Ci sono " << a . ContaMinMax ( Min , Max) << " e l e m e n t i t r a " <<
Min << " e " << Max << " . \ n" ;

void
}

PreOrdine ( A l b e r o B i n a r i o & a ) {
out << "Stampa i n pre o r d i n e : \ n" ;
a . PreOrdine ( ) ;
out << e n d l ;

void
}

InOrdine ( A l b e r o B i n a r i o & a ) {
out << "Stampa i n o r d i n e : \ n" ;
a . InOrdine ( ) ;
out << e n d l ;

void
}

PostOrdine ( A l b e r o B i n a r i o & a ) {
out << "Stampa i n post o r d i n e : \ n" ;
a . PostOrdine ( ) ;
out << e n d l ;

void Uguali ( A l b e r o B i n a r i o & a1 , A l b e r o B i n a r i o & a2 )


if ( a1 == a2 )
out << " G l i a l b e r i sono u g u a l i . \ n" ;
else
}

out << " G l i a l b e r i NON sono u g u a l i . \ n" ;

SA.9 Profondit Maggiore di Due


Tra ia a pag. 22

Si noti he il metodo riportato di seguito non ri orsivo, n ri hiama al un


altro metodo.

bool A l b e r o B i n a r i o : : ProfMaggioreDiDue ( ) onst


return

// ' l a r a d i e e . . .
// . . . o e s i s t e i l nodo d i s i n i s t r a e q u e s t o ha almeno un f i g l i o
// oppure e s i s t e i l nodo d i d e s t r a e q u e s t o ha almeno un f i g l i o .
// Tradotto i n o d i e s i ha :
r o o t && (
( root >s i n && ( root >s i n >s i n | | root >s i n >des ) ) | |
( root >des && ( root >des >s i n | | root >des >des ) )
);

SA. Soluzioni degli eser izi su alberi binari

88

SA.10 Profondita Maggiore Di


Tra ia a pag. 22

// Metodo p r i v a t o
A l b e r o B i n a r i o : : _ProfMaggioreDi (
PNodo& n ,
p)
{
( n ) { // s e l ' a l b e r o non vuoto . . .
( p == 0) // s e i l o n t a t o r e ( s e s o f i n o a ) z e r o . . .
; // . . . abbiamo s u p e r a t o l a p r o f . r i h i e s t a . . .
// . . . a l t r i m e n t i b i s o g n a o n t i n u a r e l a d i s e s a n e i s o t t o a l b e r i de rementando p .
( _ProfMaggioreDi ( n>s i n , p 1) | | _ProfMaggioreDi ( n>des , p 1 ) ) ;
}
// . . . a l t r i m e n t i f a l s o .
;
}

bool
if

if
return true
else
return
else
return false

// Metodo p u b b l i o
A l b e r o B i n a r i o : : ProfMaggioreDi (
_ProfMaggioreDi ( root , p ) ;
}

bool
return

onst

unsigned int

unsigned int

p)

onst

onst

SA.11 Profondit Massima


Tra ia a pag. 22

int A l b e r o B i n a r i o : : _Profondita ( onst PNodo& n , onst


if ( n ) { // s e l ' a l b e r o vuoto e s o s u b i t o
// s e sono q u i l ' a l b e r o non vuoto
int p ;
// d e i d o s e e r a r l o a d e s t r a o a s i n i s t r a e . . .
if ( e l > n>e l )

TElem& e l ,

bool&

foglia )

// . . . uso i l s e r v i z i o he i o s t e s s o o f f r o : r i o r s i o n e .
p = _Profondita ( n>des , e l , f o g l i a ) ;

else

p = _Profondita ( n>s i n , e l , f o g l i a ) ;

if

( p != 1) // s e l ' ho t r o v a t o i n p r o f o n d i t p a l " piano d i s o t t o " . . .


p + 1 ; // . . . l a p r o f o n d i t d a l mio punto d i v i s t a p + 1 .

return

// s e sono q u i v u o l d i r e he an ora devo t r o v a r l o


( n>e l == e l ) { // s e sono p r o p r i o i o . . .
// . . . s e non ho f i g l i l ' elemento t r o v a t o an he una f o g l i a . . .
f o g l i a = ( ! n>s i n && ! n>des ) ;
1 ; // . . . e l a p r o f o n d i t d a l mio punto d i v i s t a 1 .
}

if

return

// s e sono q u i non l ' ho t r o v a t o


1;

return

int A l b e r o B i n a r i o : : P r o f o n d i t a ( onst TElem&


return _Profondita ( root , e l , f o g l i a ) ;

el ,

bool&

foglia )

onst

onst

SA. Soluzioni degli eser izi su alberi binari

89

SA.12 Somma Livello


Tra ia a pag. 23

// Metodo p r i v a t o

void
if
}

A l b e r o B i n a r i o : : _SommaLivello (
(n) {
n>e l += i ;
_SommaLivello ( n>s i n , i +1);
_SommaLivello ( n>des , i +1);

onst

PNodo& n ,

unsigned int

i) {

// Metodo p u b b l i o

void
}

A l b e r o B i n a r i o : : SommaLivello ( ) {
_SommaLivello ( root , 1 ) ;

SA.13 Eliminazione Foglia


Tra ia a pag. 23

File AlberoBinario.h

#ifndef _ALBEROBINARIO_H_
#define _ALBEROBINARIO_H_
stru t Nodo ; // Forward d e l a r a t i o n
typedef Nodo PNodo ;
typedef unsigned int TElem ; //L ' a l b e r o
lass A l b e r o B i n a r i o {
private :
PNodo r o o t ; // r a d i e d e l l ' a l b e r o
unsigned int numelem ;

ontiene i n t er i p o s i t i v i

// Metodi r i o r s i v i d i s u p p o r t o

void _ I n s e r i s i ( PNodo& n , onst TElem& e l ) ;


void _Svuota ( onst PNodo& n ) ;
bool _Cer a ( onst PNodo& n , onst TElem& e l ) onst ;
bool _EliminaFoglia ( PNodo& n , onst TElem& e l ) ;
void _PreOrdine ( onst PNodo& n ) onst ;
void _PostOrdine ( onst PNodo& n ) onst ;
void _InOrdine ( onst PNodo& n ) onst ;
inline bool EUnaFoglia ( onst PNodo& n ) ;
A l b e r o B i n a r i o ( onst A l b e r o B i n a r i o &); // i m p e d i s e l a o p i a mediante
void operator=( onst A l b e r o B i n a r i o &); // i m p e d i s e l ' a s s e g n a z i o n e
publi :
A l b e r o B i n a r i o ( ) ; // o s t r u t t o r e senza parametri
~ A l b e r o B i n a r i o ( ) ; // D i s t r u t t o r e

ostruttore

SA. Soluzioni degli eser izi su alberi binari

};

90

void I n s e r i s i ( onst TElem& e l ) ;


void Svuota ( ) ;
bool Cer a ( onst TElem& e l ) onst ;
bool E l i m i n a F o g l i a ( onst TElem& e l ) ;
unsigned int NumElem ( ) onst ;
void PreOrdine ( ) onst ;
void PostOrdine ( ) onst ;
void InOrdine ( ) onst ;

#endif

/ _ALBEROBINARIO_H_ /

File AlberoBinario. pp

#in lude <i o s t r e a m>


#in lude " A l b e r o B i n a r i o . h"
using namespa e s t d ;
stru t Nodo { // S t r u t t u r a Nodo
};

TElem e l ;
PNodo s i n ;
PNodo des ;

A l b e r o B i n a r i o : : A l b e r o B i n a r i o ( ) : r o o t ( 0 ) , numelem ( 0 ) {
}
AlberoBinario : :~ AlberoBinario () {
Svuota ( ) ;
}

// Metodi p r i v a t i r i o r s i v i d i s u p p o r t o

void
if
}

new

else
if ( e l > n>e l )
_ I n s e r i s i ( n>des ,
else

el );

_ I n s e r i s i ( n>s i n , e l ) ;

void
if
}

onst

A l b e r o B i n a r i o : : _ I n s e r i s i ( PNodo& n ,
TElem& e l ) {
( ! n) {
n =
Nodo ; // s i rea un nuovo elemento d e l l ' a l b e r o . . .
n>e l = e l ; // . . . e l o s i i n i z i a l i z z a .
n>s i n = 0 ;
n>des = 0 ;

bool
if

onst

A l b e r o B i n a r i o : : _Svuota (
PNodo& n ) {
( n ) { // Agis e s o l o s e l ' a l b e r o non vuoto
_Svuota ( n>s i n ) ;
_Svuota ( n>des ) ;
n;

delete

onst

onst

onst

A l b e r o B i n a r i o : : _Cer a (
PNodo& n ,
TElem& e l )
(n) {
( n>e l == e l ) // l ' elemento e r a t o n e l nodo o r r e n t e ?
;

if

return true

SA. Soluzioni degli eser izi su alberi binari

}
}

if ( e l > n>e l ) // maggiore


return _Cer a ( n>des , e l ) ;
else
return _Cer a ( n>s i n , e l ) ;
else
return false ;

91

del ontenuto d e l l a radi e ?


// e r a n e l s o t t o a l b e r o d e s t r o
// e r a n e l s o t t o a l b e r o s i n i s t r o

inline bool

onst

A l b e r o B i n a r i o : : EUnaFoglia (
PNodo& n ) {
// metodo d i s u p p o r t o he v e r i f i a s e i l nodo
// p u n t a t o da n o meno una f o g l i a .
( ! n>s i n && ! n>des ) ;
}

return

bool
if

}
}

void
if
}

void
if
}

if

delete
return true
else
if
return
else
// r i p e t i l ' o p e r a z i o n e n e l s o t t o a l b .
return _EliminaFoglia ( n>s i n , e l ) ;

sinistro

return false ;

void
if
}

onst

A l b e r o B i n a r i o : : _EliminaFoglia ( PNodo& n ,
TElem& e l ) {
( n ) { // s e n punta ad un nodo ( e non a z e r o )
// s e l ' elemento p u n t a t o e l e i l nodo una f o g l i a
( ( n>e l == e l ) && EUnaFoglia ( n ) ) {
n ; // e l i m i n a l ' elemento
n = 0 ; // a z z e r a i l p u n t a t o r e
;
}
( e l > n>e l )
// r i p e t i l ' o p e r a z i o n e n e l s o t t o a l b . d e s t r o
_EliminaFoglia ( n>des , e l ) ;

A l b e r o B i n a r i o : : _PreOrdine (
(n) {
out << n>e l << " " ;
_PreOrdine ( n>s i n ) ;
_PreOrdine ( n>des ) ;

onst

A l b e r o B i n a r i o : : _PostOrdine (
(n) {
_PostOrdine ( n>s i n ) ;
_PostOrdine ( n>des ) ;
out << n>e l << " " ;

A l b e r o B i n a r i o : : _InOrdine (
(n) {
_InOrdine ( n>s i n ) ;
out << n>e l << " " ;
_InOrdine ( n>des ) ;

onst

PNodo& n )

onst

PNodo& n )

onst

PNodo& n )

void

AlberoBinario : : I n s e r i s i (
_ I n s e r i s i ( root , e l ) ;

onst

TElem& e l ) {

onst

onst

// Metodi p u b b l i i

SA. Soluzioni degli eser izi su alberi binari

92

numelem++;

void
}

A l b e r o B i n a r i o : : Svuota ( ) {
_Svuota ( r o o t ) ;
root = 0;
numelem = 0 ;

unsigned int A l b e r o B i n a r i o : : NumElem ( ) onst


return numelem ;

bool A l b e r o B i n a r i o : : Cer a ( onst


return _Cer a ( root , e l ) ;

TElem& e l )

onst

bool
if
}
}

AlberoBinario : : EliminaFoglia(
( _EliminaFoglia ( root , e l ) ) {
numelem;
;

A l b e r o B i n a r i o : : PostOrdine ( )
_PostOrdine ( r o o t ) ;

void
}

onst

A l b e r o B i n a r i o : : PreOrdine ( )
_PreOrdine ( r o o t ) ;

void
}

TElem& e l ) {

return true
else
return false ;

void
}

onst

A l b e r o B i n a r i o : : InOrdine ( )
_InOrdine ( r o o t ) ;

onst

onst

File main. pp

#in lude <i o s t r e a m>


#in lude " A l b e r o B i n a r i o . h"
using namespa e s t d ;
// P r o t o t i p i d i f u n z i o n i d i s u p p o r t o per l a v e r i f i a d e l o r r e t t o funzionamento
// d e i metodi d e l l a l a s s e A l b e r o B i n a r i o .
stampaMenu ( ) ;
I n s e r i s i ( AlberoBinario& a ) ;
Svuota ( A l b e r o B i n a r i o & a ) ;
Cer a ( A l b e r o B i n a r i o & a ) ;
EliminaFoglia( AlberoBinario& a ) ;
NumeroElementi ( A l b e r o B i n a r i o & a ) ;
PreOrdine ( A l b e r o B i n a r i o & a ) ;
InOrdine ( A l b e r o B i n a r i o & a ) ;
PostOrdine ( A l b e r o B i n a r i o & a ) ;

void
void
void
void
void
void
void
void
void
int main ( ) {
AlberoBinario
har ;
do {

albero ;

SA. Soluzioni degli eser izi su alberi binari


stampaMenu ( ) ;
i n >> ;
in . ignore ( ) ;

swit h ( ) {
ase ' 1 ' :
I n s e r i s i ( albero ) ;
break ;
ase ' 2 ' :
Svuota ( a l b e r o ) ;
break ;
ase ' 3 ' :
Cer a ( a l b e r o ) ;
break ;
ase ' 4 ' :
EliminaFoglia( albero ) ;
break ;
ase ' 5 ' :
NumeroElementi ( a l b e r o ) ;
break ;
ase ' 6 ' :
PreOrdine ( a l b e r o ) ;
break ;
ase ' 7 ' :
InOrdine ( a l b e r o ) ;
break ;
ase ' 8 ' :
PostOrdine ( a l b e r o ) ;
break ;
ase ' 9 ' :
break ;
default :
out << " S e l t a non v a l i d a . \ n" ;
break ;
}
} while ( != ' 9 ' ) ;
return 0 ;

void

stampaMenu ( ) {
out << e n d l ;
out << " 1 . I n s e r i s i " << e n d l ;
out << " 2 . Svuota " << e n d l ;
out << " 3 . Cer a " << e n d l ;
out << " 4 . Elimina F o g l i a " << e n d l ;
out << " 5 . Numero Elementi " << e n d l ;
out << " 6 . Pre o r d i n e " << e n d l ;
out << " 7 . InOrdine " << e n d l ;
out << " 8 . Post Ordine " << e n d l ;
out << " 9 . E s i " << e n d l ;
out << e n d l ;
out << " S e l t a : " ;

void I n s e r i s i ( A l b e r o B i n a r i o & a )
int i ;
}

out << " I n s e r i s i i n t e r o : " ;


i n >> i ;
a. Inseris i ( i );
out << " Elemento i n s e r i t o . \ n" ;

93

SA. Soluzioni degli eser izi su alberi binari

94

void
}

Svuota ( A l b e r o B i n a r i o & a ) {
out << " Svuotamento a l b e r o . " << e n d l ;
a . Svuota ( ) ;

void Cer a ( A l b e r o B i n a r i o & a )


int i ;

out << " I n s e r i s i i n t e r o : " ;


i n >> i ;

if ( a . Cer a ( i ) )
out << " Elemento
else

t r o v a t o . \ n" ;

out << " Elemento NON t r o v a t o . \ n" ;

void E l i m i n a F o g l i a ( A l b e r o B i n a r i o & a )
int i ;

out << " I n s e r i s i i n t e r o : " ;


i n >> i ;
( a . EliminaFoglia( i ))
out << " Elemento e l i m i n a t o . \ n" ;

if
else

out << " Elemento NON e l i m i n a t o . \ n" ;

void
}

NumeroElementi ( A l b e r o B i n a r i o & a ) {
out << " I l numero d i e l e m e n t i e ' : " << a . NumElem ( ) << e n d l ;

void
}

PreOrdine ( A l b e r o B i n a r i o & a ) {
out << "Stampa i n pre o r d i n e : \ n" ;
a . PreOrdine ( ) ;
out << e n d l ;

void
}

InOrdine ( A l b e r o B i n a r i o & a ) {
out << "Stampa i n o r d i n e : \ n" ;
a . InOrdine ( ) ;
out << e n d l ;

void
}

PostOrdine ( A l b e r o B i n a r i o & a ) {
out << "Stampa i n post o r d i n e : \ n" ;
a . PostOrdine ( ) ;
out << e n d l ;

SA.14 Eliminazione Foglie


Tra ia a pag. 23

File AlberoBinario.h

SA. Soluzioni degli eser izi su alberi binari

#ifndef _ALBEROBINARIO_H_
#define _ALBEROBINARIO_H_
stru t Nodo ; // Forward d e l a r a t i o n
typedef Nodo PNodo ;
typedef unsigned int TElem ; //L ' a l b e r o
lass A l b e r o B i n a r i o {
private :
PNodo r o o t ; // r a d i e d e l l ' a l b e r o
unsigned int numelem ;

95

ontiene i n t er i p o s i t i v i

// Metodi r i o r s i v i d i s u p p o r t o

void _ I n s e r i s i ( PNodo& n , onst TElem& e l ) ;


void _Svuota ( onst PNodo& n ) ;
bool _Cer a ( onst PNodo& n , onst TElem& e l ) onst ;
unsigned int _EliminaFoglie ( PNodo& n ) ;
void _PreOrdine ( onst PNodo& n ) onst ;
void _PostOrdine ( onst PNodo& n ) onst ;
void _InOrdine ( onst PNodo& n ) onst ;
inline bool EUnaFoglia ( onst PNodo& n ) ;
A l b e r o B i n a r i o ( onst A l b e r o B i n a r i o &); // i m p e d i s e l a o p i a mediante
void operator=( onst A l b e r o B i n a r i o &); // i m p e d i s e l ' a s s e g n a z i o n e
publi :
A l b e r o B i n a r i o ( ) ; // o s t r u t t o r e senza parametri
~ A l b e r o B i n a r i o ( ) ; // D i s t r u t t o r e

};

void I n s e r i s i ( onst TElem& e l ) ;


void Svuota ( ) ;
unsigned int NumElem ( ) onst ;
bool Cer a ( onst TElem& e l ) onst ;
unsigned int E l i m i n a F o g l i e ( ) ;
void PreOrdine ( ) onst ;
void PostOrdine ( ) onst ;
void InOrdine ( ) onst ;

#endif

/ _ALBEROBINARIO_H_ /

File AlberoBinario. pp

#in lude <i o s t r e a m>


#in lude " A l b e r o B i n a r i o . h"
using namespa e s t d ;
stru t Nodo { // S t r u t t u r a Nodo
};

TElem e l ;
PNodo s i n ;
PNodo des ;

A l b e r o B i n a r i o : : A l b e r o B i n a r i o ( ) : r o o t ( 0 ) , numelem ( 0 ) {
}
AlberoBinario : :~ AlberoBinario () {
Svuota ( ) ;
}

ostruttore

SA. Soluzioni degli eser izi su alberi binari

96

// Metodi p r i v a t i r i o r s i v i d i s u p p o r t o

void
if
}

onst

A l b e r o B i n a r i o : : _ I n s e r i s i ( PNodo& n ,
TElem& e l ) {
( ! n) {
n =
Nodo ; // s i rea un nuovo elemento d e l l ' a l b e r o . . .
n>e l = e l ; // . . . e l o s i i n i z i a l i z z a .
n>s i n = 0 ;
n>des = 0 ;

new

else
if ( e l > n>e l )
_ I n s e r i s i ( n>des ,
else

_ I n s e r i s i ( n>s i n , e l ) ;

void
if
}

el );

bool
if

}
}

onst

A l b e r o B i n a r i o : : _Svuota (
PNodo& n ) {
( n ) { // Agis e s o l o s e l ' a l b e r o non vuoto
_Svuota ( n>s i n ) ;
_Svuota ( n>des ) ;
n;

delete

onst

onst

onst

A l b e r o B i n a r i o : : _Cer a (
PNodo& n ,
TElem& e l )
(n) {
( n>e l == e l ) // l ' elemento e r a t o n e l nodo o r r e n t e ?
;

if

return true

if ( e l > n>e l ) // maggiore


return _Cer a ( n>des , e l ) ;
else
return _Cer a ( n>s i n , e l ) ;
else
return false ;

del ontenuto d e l l a radi e ?


// e r a n e l s o t t o a l b e r o d e s t r o
// e r a n e l s o t t o a l b e r o s i n i s t r o

inline bool

onst

A l b e r o B i n a r i o : : EUnaFoglia (
PNodo& n ) {
// metodo d i s u p p o r t o he v e r i f i a s e i l nodo
// p u n t a t o da n o meno una f o g l i a .
( ! n>s i n && ! n>des ) ;
}

return

unsigned int A l b e r o B i n a r i o : : _EliminaFoglie ( PNodo& n )


if ( n ) {
if ( EUnaFoglia ( n ) ) {
delete n ;

}
}

n = 0;
numelem;
1;

return
else
return

return

void
if

_EliminaFoglie ( n>s i n ) + _EliminaFoglie ( n>des ) ;

0;

A l b e r o B i n a r i o : : _PreOrdine (
(n) {
out << n>e l << " " ;
_PreOrdine ( n>s i n ) ;

onst

PNodo& n )

onst

SA. Soluzioni degli eser izi su alberi binari

void
if
}

void
if
}

97

_PreOrdine ( n>des ) ;

A l b e r o B i n a r i o : : _PostOrdine (
(n) {
_PostOrdine ( n>s i n ) ;
_PostOrdine ( n>des ) ;
out << n>e l << " " ;

A l b e r o B i n a r i o : : _InOrdine (
(n) {
_InOrdine ( n>s i n ) ;
out << n>e l << " " ;
_InOrdine ( n>des ) ;

onst

PNodo& n )

onst

PNodo& n )

onst

TElem& e l ) {

onst

onst

// Metodi p u b b l i i

void
}

AlberoBinario : : I n s e r i s i (
_ I n s e r i s i ( root , e l ) ;
numelem++;

void
}

A l b e r o B i n a r i o : : Svuota ( ) {
_Svuota ( r o o t ) ;
root = 0;
numelem = 0 ;

unsigned int A l b e r o B i n a r i o : : NumElem ( ) onst


return numelem ;

bool A l b e r o B i n a r i o : : Cer a ( onst


return _Cer a ( root , e l ) ;

TElem& e l )

onst

unsigned int A l b e r o B i n a r i o : : E l i m i n a F o g l i e ( )
return _EliminaFoglie ( r o o t ) ;

void
}

void
}

A l b e r o B i n a r i o : : PostOrdine ( )
_PostOrdine ( r o o t ) ;

void
}

onst

A l b e r o B i n a r i o : : PreOrdine ( )
_PreOrdine ( r o o t ) ;

A l b e r o B i n a r i o : : InOrdine ( )
_InOrdine ( r o o t ) ;

onst

onst

File main. pp

#in lude
#in lude

<i o s t r e a m>
" A l b e r o B i n a r i o . h"

SA. Soluzioni degli eser izi su alberi binari

using namespa e

98

std ;

// P r o t o t i p i d i f u n z i o n i d i s u p p o r t o per l a v e r i f i a d e l o r r e t t o funzionamento
// d e i metodi d e l l a l a s s e A l b e r o B i n a r i o .
stampaMenu ( ) ;
I n s e r i s i ( AlberoBinario& a ) ;
Svuota ( A l b e r o B i n a r i o & a ) ;
Cer a ( A l b e r o B i n a r i o & a ) ;
EliminaFoglie ( AlberoBinario& a ) ;
NumeroElementi ( A l b e r o B i n a r i o & a ) ;
PreOrdine ( A l b e r o B i n a r i o & a ) ;
InOrdine ( A l b e r o B i n a r i o & a ) ;
PostOrdine ( A l b e r o B i n a r i o & a ) ;

void
void
void
void
void
void
void
void
void
int main ( ) {
AlberoBinario
har ;
do {

albero ;

stampaMenu ( ) ;
i n >> ;
in . ignore ( ) ;

swit h ( ) {
ase ' 1 ' :
I n s e r i s i ( albero ) ;
break ;
ase ' 2 ' :
Svuota ( a l b e r o ) ;
break ;
ase ' 3 ' :
Cer a ( a l b e r o ) ;
break ;
ase ' 4 ' :
EliminaFoglie ( albero ) ;
break ;
ase ' 5 ' :
NumeroElementi ( a l b e r o ) ;
break ;
ase ' 6 ' :
PreOrdine ( a l b e r o ) ;
break ;
ase ' 7 ' :
InOrdine ( a l b e r o ) ;
break ;
ase ' 8 ' :
PostOrdine ( a l b e r o ) ;
break ;
ase ' 9 ' :
break ;
default :
out << " S e l t a non v a l i d a . \ n" ;
break ;
}
} while ( != ' 9 ' ) ;
return 0 ;

void

stampaMenu ( ) {
out << e n d l ;

SA. Soluzioni degli eser izi su alberi binari

out
out
out
out
out
out
out
out
out
out
out

<<
<<
<<
<<
<<
<<
<<
<<
<<
<<
<<

" 1 . I n s e r i s i " << e n d l ;


" 2 . Svuota " << e n d l ;
" 3 . Cer a " << e n d l ;
" 4 . Elimina F o g l i e " << e n d l ;
" 5 . Numero Elementi " << e n d l ;
" 6 . Pre o r d i n e " << e n d l ;
" 7 . InOrdine " << e n d l ;
" 8 . Post Ordine " << e n d l ;
" 9 . E s i " << e n d l ;
endl ;
" S elta : " ;

void I n s e r i s i ( A l b e r o B i n a r i o & a )
int i ;
}

out << " I n s e r i s i i n t e r o : " ;


i n >> i ;
a. Inseris i ( i );
out << " Elemento i n s e r i t o . \ n" ;

void
}

Svuota ( A l b e r o B i n a r i o & a ) {
out << " Svuotamento a l b e r o . " << e n d l ;
a . Svuota ( ) ;

void Cer a ( A l b e r o B i n a r i o & a )


int i ;

out << " I n s e r i s i i n t e r o : " ;


i n >> i ;

if ( a . Cer a ( i ) )
out << " Elemento
else

t r o v a t o . \ n" ;

out << " Elemento NON t r o v a t o . \ n" ;

void
}

EliminaFoglie ( AlberoBinario& a ) {
out << a . E l i m i n a F o g l i e ( ) << " f o g l i e e l i m i n a t e . \ n" ;

void
}

NumeroElementi ( A l b e r o B i n a r i o & a ) {
out << " I l numero d i e l e m e n t i e ' : " << a . NumElem ( ) << e n d l ;

void
}

PreOrdine ( A l b e r o B i n a r i o & a ) {
out << "Stampa i n pre o r d i n e : \ n" ;
a . PreOrdine ( ) ;
out << e n d l ;

void
}

InOrdine ( A l b e r o B i n a r i o & a ) {
out << "Stampa i n o r d i n e : \ n" ;
a . InOrdine ( ) ;
out << e n d l ;

void

PostOrdine ( A l b e r o B i n a r i o & a ) {
out << "Stampa i n post o r d i n e : \ n" ;
a . PostOrdine ( ) ;
out << e n d l ;

99

SA. Soluzioni degli eser izi su alberi binari

100

SA.15 Operatore di Confronto


Tra ia a pag. 24

// Metodo p r i v a t o

bool A l b e r o B i n a r i o : : _uguale ( onst PNodo& n1 , onst PNodo& n2 ) onst


if ( ! n1 && ! n2 ) // Se l e due r a d i i sono 0 ( i o entrambi g l i a l b .
return true ; // . . . i due a l b e r i sono u g u a l i
else
if ( ! n1 | | ! n2 ) // Se una d e l l e due r a d i i 0 . . .
return false ; // . . . i due a l b e r i non sono u g u a l i

{
sono v u o t i ) . . .

// ( p e r h l ' a l t r a ertamente non z e r o )

// Assodato he nessuna d e l l e due r a d i i vuota . . .


( n1>e l != n2>e l ) // . . . s e i due e l e m e n t i p u n t a t i da n1 e n2 sono d i v e r s i . . .
;
// . . . a l l o r a i due a l b e r i non sono u g u a l i .

if

return false

//Dunque , abbiamo due a l b e r i non v u o t i e o n t e n e n t i e l e m e n t i


// d i u g u a l e v a l o r e n e l l a r a d i e .
// Bisogna ora o n t r o l l a r e s e i l o r o s o t t o a l b e r i s i n i s t r o e d e s t r o sono u g u a l i :
// r i o r s i o n e .
_uguale ( n1>s i n , n2>s i n ) && _uguale ( n1>des , n2>des ) ;

return

// Metodo p u b b l i o
AlberoBinario : :
==(
AlberoBinario& rhs )
{
// Questo o p e r a t o r e v i e n e i n v o a t o on l a s e g u e n t e s i n t a s s i :
//
a1 == a2 ;
// dove a1 ed a2 sono due i s t a n z e d e l l a l a s s e A l b e r o B i n a r i o .
// In q u e s t o aso v i e n e i n v o a t o l ' o p e r a t o r ==() s u l l ' o g g e t t o a1 ,
// mentre a2 , parametro a t t u a l e , v i e n e p a s s a t o per r i f e r i m e n t o
// prendendo i l p o s t o d e l parametro f o r m a l e r h s .

bool

operator onst

onst

// Chiamo i l metodo p r i v a t o _uguale ( ) e g l i passo l a mia r a d i e


// e l a r a d i e d e l l ' a l b e r o r h s .
_uguale ( root , r h s . r o o t ) ;

return

SA.16 Conta Nodi non Foglia


Tra ia a pag. 24

// Metodo p r i v a t o

unsigned int A l b e r o B i n a r i o : : _ContaNodiNonFoglia ( onst


if ( ! n )
return 0 ;
unsigned int ount = 0 ;
// e v e n t u a l e o n t r i b u t o s o t t o a l b e r o s i n i s t r o
( n>s i n )
ount = ount + _ContaNodiNonFoglia ( n>s i n ) ;

if

PNodo& n )

onst

SA. Soluzioni degli eser izi su alberi binari

101

// e v e n t u a l e o n t r i b u t o s o t t o a l b e r o d e s t r o
( n>des )
ount = ount + _ContaNodiNonFoglia ( n>des ) ;

if

// e v e n t u a l e o n t r i b u t o d e l p r e s e n t e nodo
( n>s i n | | n>des )
ount++;

if

return

ount ;

// Metodo p u b b l i o

unsigned int A l b e r o B i n a r i o : : ContaNodiNonFoglia ( ) onst


return _ContaNodiNonFoglia ( r o o t ) ;

SA.17 Conta Nodi


Tra ia a pag. 24

File AlberoBinario.h

#ifndef _ALBEROBINARIO_H_
#define _ALBEROBINARIO_H_
stru t Nodo ; // Forward d e l a r a t i o n
typedef Nodo PNodo ;
typedef unsigned int TElem ; //L ' a l b e r o
lass A l b e r o B i n a r i o {
private :
PNodo r o o t ; // r a d i e d e l l ' a l b e r o
unsigned int numelem ;

ontiene i n t er i p o s i t i v i

// Metodi r i o r s i v i d i s u p p o r t o
_ I n s e r i s i ( PNodo& n ,
TElem& e l ) ;
_Svuota (
PNodo& n ) ;
_Cer a (
PNodo& n ,
TElem& e l )
;
_ContaNodi (
PNodo& n ,
& zero ,

void
void
bool
void
void
void
void

onst
onst
onst
onst
onst
onst
unsigned int
unsigned int& uno ,
unsigned int& due ) onst ;
_PreOrdine ( onst PNodo& n ) onst ;
_PostOrdine ( onst PNodo& n ) onst ;
_InOrdine ( onst PNodo& n ) onst ;
A l b e r o B i n a r i o ( onst A l b e r o B i n a r i o &); // i m p e d i s e l a o p i a mediante o s t r u t t o r e
void operator=( onst A l b e r o B i n a r i o &); // i m p e d i s e l ' a s s e g n a z i o n e
publi :
A l b e r o B i n a r i o ( ) ; // o s t r u t t o r e senza parametri
~ A l b e r o B i n a r i o ( ) ; // D i s t r u t t o r e

void
void
bool

onst TElem& e l ) ;
onst TElem& e l ) onst ;

Inseris i (
Svuota ( ) ;
Cer a (

SA. Soluzioni degli eser izi su alberi binari

};

102

void ContaNodi ( unsigned int& zero , unsigned int& uno , unsigned int& due ) onst ;
unsigned int NumElem ( ) onst ;
void PreOrdine ( ) onst ;
void PostOrdine ( ) onst ;
void InOrdine ( ) onst ;

#endif

/ _ALBEROBINARIO_H_ /

File AlberoBinario. pp

#in lude <i o s t r e a m>


#in lude " A l b e r o B i n a r i o . h"
using namespa e s t d ;
stru t Nodo { // S t r u t t u r a Nodo
};

TElem e l ;
PNodo s i n ;
PNodo des ;

A l b e r o B i n a r i o : : A l b e r o B i n a r i o ( ) : r o o t ( 0 ) , numelem ( 0 ) {
}
AlberoBinario : :~ AlberoBinario () {
Svuota ( ) ;
}

// Metodi p r i v a t i r i o r s i v i d i s u p p o r t o

void
if
}

new

else
if ( e l > n>e l )
_ I n s e r i s i ( n>des ,
else

el );

_ I n s e r i s i ( n>s i n , e l ) ;

void
if
}

onst

A l b e r o B i n a r i o : : _ I n s e r i s i ( PNodo& n ,
TElem& e l ) {
( ! n) {
n =
Nodo ; // s i rea un nuovo elemento d e l l ' a l b e r o . . .
n>e l = e l ; // . . . e l o s i i n i z i a l i z z a .
n>s i n = 0 ;
n>des = 0 ;

bool
if

onst

A l b e r o B i n a r i o : : _Svuota (
PNodo& n ) {
( n ) { // Agis e s o l o s e l ' a l b e r o non vuoto
_Svuota ( n>s i n ) ;
_Svuota ( n>des ) ;
n;

delete

onst

onst

onst

A l b e r o B i n a r i o : : _Cer a (
PNodo& n ,
TElem& e l )
(n) {
( n>e l == e l ) // l ' elemento e r a t o n e l nodo o r r e n t e ?
;

if

return true

if ( e l > n>e l ) // maggiore


return _Cer a ( n>des , e l ) ;
else

del ontenuto d e l l a radi e ?


// e r a n e l s o t t o a l b e r o d e s t r o

SA. Soluzioni degli eser izi su alberi binari

}
}

void
if

return _Cer a ( n>s i n ,


else
return false ;

103

e l ) ; // e r a n e l s o t t o a l b e r o s i n i s t r o

A l b e r o B i n a r i o : : _ContaNodi (

onst PNodo& n , unsigned int& zero ,


unsigned int& uno , unsigned int& due ) onst

(n) {
_ContaNodi ( n>s i n , zero , uno , due ) ;
_ContaNodi ( n>des , zero , uno , due ) ;

if ( n>s i n && n>des )


due++;
else
if ( ! n>s i n && ! n>des )
z e r o ++;
else
}

void
if
}

void
if
}

void
if
}

uno++;

A l b e r o B i n a r i o : : _PreOrdine (
(n) {
out << n>e l << " " ;
_PreOrdine ( n>s i n ) ;
_PreOrdine ( n>des ) ;

onst

A l b e r o B i n a r i o : : _PostOrdine (
(n) {
_PostOrdine ( n>s i n ) ;
_PostOrdine ( n>des ) ;
out << n>e l << " " ;

A l b e r o B i n a r i o : : _InOrdine (
(n) {
_InOrdine ( n>s i n ) ;
out << n>e l << " " ;
_InOrdine ( n>des ) ;

onst

PNodo& n )

onst

PNodo& n )

onst

PNodo& n )

void
}

AlberoBinario : : I n s e r i s i (
_ I n s e r i s i ( root , e l ) ;
numelem++;

onst

TElem& e l ) {

void
}

A l b e r o B i n a r i o : : Svuota ( ) {
_Svuota ( r o o t ) ;
root = 0;
numelem = 0 ;

unsigned int A l b e r o B i n a r i o : : NumElem ( ) onst


return numelem ;
}

onst

onst

// Metodi p u b b l i i

SA. Soluzioni degli eser izi su alberi binari

bool A l b e r o B i n a r i o : : Cer a ( onst


return _Cer a ( root , e l ) ;

TElem& e l )

104

onst

void

A l b e r o B i n a r i o : : ContaNodi (

unsigned int&

zero = 0;
uno = 0 ;
due = 0 ;
_ContaNodi ( root , zero , uno , due ) ;

void
}

A l b e r o B i n a r i o : : PostOrdine ( )
_PostOrdine ( r o o t ) ;

void
}

onst

A l b e r o B i n a r i o : : PreOrdine ( )
_PreOrdine ( r o o t ) ;

void
}

zero ,

A l b e r o B i n a r i o : : InOrdine ( )
_InOrdine ( r o o t ) ;

onst

onst

unsigned int& uno ,


unsigned int& due ) onst

File main. pp

#in lude <i o s t r e a m>


#in lude " A l b e r o B i n a r i o . h"
using namespa e s t d ;
// P r o t o t i p i d i f u n z i o n i d i s u p p o r t o per l a v e r i f i a d e l o r r e t t o funzionamento
// d e i metodi d e l l a l a s s e A l b e r o B i n a r i o .
stampaMenu ( ) ;
I n s e r i s i ( AlberoBinario& a ) ;
Svuota ( A l b e r o B i n a r i o & a ) ;
Cer a ( A l b e r o B i n a r i o & a ) ;
ContaNodi ( A l b e r o B i n a r i o & a ) ;
NumeroElementi ( A l b e r o B i n a r i o & a ) ;
PreOrdine ( A l b e r o B i n a r i o & a ) ;
InOrdine ( A l b e r o B i n a r i o & a ) ;
PostOrdine ( A l b e r o B i n a r i o & a ) ;

void
void
void
void
void
void
void
void
void
int main ( ) {
AlberoBinario
har ;
do {

albero ;

stampaMenu ( ) ;
i n >> ;
in . ignore ( ) ;

swit h ( ) {
ase ' 1 ' :
I n s e r i s i ( albero ) ;
break ;
ase ' 2 ' :
Svuota ( a l b e r o ) ;
break ;
ase ' 3 ' :
Cer a ( a l b e r o ) ;

SA. Soluzioni degli eser izi su alberi binari

break ;
ase ' 4 ' :
ContaNodi ( a l b e r o ) ;
break ;
ase ' 5 ' :
NumeroElementi ( a l b e r o ) ;
break ;
ase ' 6 ' :
PreOrdine ( a l b e r o ) ;
break ;
ase ' 7 ' :
InOrdine ( a l b e r o ) ;
break ;
ase ' 8 ' :
PostOrdine ( a l b e r o ) ;
break ;
ase ' 9 ' :
break ;
default :
out << " S e l t a non v a l i d a . \ n" ;
break ;
}
} while ( != ' 9 ' ) ;
return 0 ;

void

stampaMenu ( ) {
out << e n d l ;
out << " 1 . I n s e r i s i " << e n d l ;
out << " 2 . Svuota " << e n d l ;
out << " 3 . Cer a " << e n d l ;
out << " 4 . Conta Nodi " << e n d l ;
out << " 5 . Numero Elementi " << e n d l ;
out << " 6 . Pre o r d i n e " << e n d l ;
out << " 7 . InOrdine " << e n d l ;
out << " 8 . Post Ordine " << e n d l ;
out << " 9 . E s i " << e n d l ;
out << e n d l ;
out << " S e l t a : " ;

void I n s e r i s i ( A l b e r o B i n a r i o & a )
int i ;
}

out << " I n s e r i s i i n t e r o : " ;


i n >> i ;
a. Inseris i ( i );
out << " Elemento i n s e r i t o . \ n" ;

void
}

Svuota ( A l b e r o B i n a r i o & a ) {
out << " Svuotamento a l b e r o . " << e n d l ;
a . Svuota ( ) ;

void Cer a ( A l b e r o B i n a r i o & a )


int i ;

out << " I n s e r i s i i n t e r o : " ;


i n >> i ;

if

( a . Cer a ( i ) )

105

SA. Soluzioni degli eser izi su alberi binari


out << " Elemento t r o v a t o . \ n" ;

else

out << " Elemento NON t r o v a t o . \ n" ;

void ContaNodi ( A l b e r o B i n a r i o & a )


unsigned int num0 , num1 , num2 ;

a . ContaNodi (num0 ,
out << " Nodi on
out << " Nodi on
out << " Nodi on

num1 , num2 ) ;
0 f i g l i : " << num0 <<e n d l ;
1 f i g l i o : " << num1 <<e n d l ;
2 f i g l i : " << num2 <<e n d l ;

void
}

NumeroElementi ( A l b e r o B i n a r i o & a ) {
out << " I l numero d i e l e m e n t i e ' : " << a . NumElem ( ) << e n d l ;

void
}

PreOrdine ( A l b e r o B i n a r i o & a ) {
out << "Stampa i n pre o r d i n e : \ n" ;
a . PreOrdine ( ) ;
out << e n d l ;

void
}

InOrdine ( A l b e r o B i n a r i o & a ) {
out << "Stampa i n o r d i n e : \ n" ;
a . InOrdine ( ) ;
out << e n d l ;

void
}

PostOrdine ( A l b e r o B i n a r i o & a ) {
out << "Stampa i n post o r d i n e : \ n" ;
a . PostOrdine ( ) ;
out << e n d l ;

106

Capitolo SP
Soluzioni degli eser izi su pile
SP.1 Push Greater
Tra ia a pag. 25

#in lude <i o s t r e a m>


#in lude <s t d l i b . h>
using namespa e s t d ;
typedef int TElem ;
stru t Re ord ;
typedef Re ord PRe ;
typedef stru t Re ord
};

TElem e l ;
PRe s u ;

lass P i l a {
private :
PRe top ;
int nelem ;
publi :
Pila ( ) ;
~Pila ( ) ;

void
bool

};

onst
onst
onst

Push (
TElem& e ) ;
PushGreater (
TElem& e ) ;
TElem Top ( )
;
TElem Pop ( ) ;
Svuota ( ) ;
Count ( )
;
Empty ( )
;

void
int
bool

onst
onst

P i l a : : P i l a ( ) : top ( 0 ) , nelem ( 0 ) {
}
Pila ::~ Pila () {
Svuota ( ) ;
}
107

SP. Soluzioni degli eser izi su pile

void

onst

P i l a : : Push (
TElem& e ) {
PRe p =
Re ord ;
p>e l = e ;
p>s u = top ;
top = p ;
nelem++;

bool
if
}
}

new

onst

P i l a : : PushGreater (
TElem& e ) {
( Empty ( ) | | ( e > Top ( ) ) ) {
Push ( e ) ;
;

return true
else
return false ;

onst

TElem P i l a : : Top ( )
( top )
top >e l ;

if

108

return

// q u e s t o metodo r e s t i t . un v a l o r e non s p e i f i a t o n e l aso l a p i l a s i a vuota

TElem P i l a : : Pop ( ) {
( top ) {
TElem e = top >e l ; // memorizza i l v a l o r e d i t e s t a per r e s t i t u i r l o a l l a f i n e

if

// memorizza i l p u n t a t o r e a l l a t e s t a : e s s a dovr e s s e r e a n e l l a t a
PRe p = top ;
top = top >s u ; // p o r t a l a t e s t a a l s u e s s i v o
p ; // e l i m i n a l a v e h i a t e s t a

delete

}
}

nelem ;
e;

return

// q u e s t o metodo r e s t i t . un v a l o r e non s p e i f i a t o n e l aso l a p i l a s i a vuota

void P i l a : : Svuota ( )
while ( top ) {

PRe p = top ;
top = top >s u ;
p;

delete

}
nelem = 0 ;

int P i l a : : Count ( ) onst


return nelem ;

bool P i l a : : Empty ( ) onst


return ( nelem == 0 ) ;

void
void
void
void
void

stampaMenu ( ) ;
Push ( P i l a& p ) ;
PushGreater ( P i l a& p ) ;
Top ( P i l a& p ) ;
Pop ( P i l a& p ) ;

SP. Soluzioni degli eser izi su pile

void Svuota ( P i l a& p ) ;


void Count ( P i l a& p ) ;
void Empty ( P i l a& p ) ;
int main ( )
{
har ;
Pila pila ;

do

{
stampaMenu ( ) ;
i n >> ;
in . ignore ( ) ;

swit h ( ) {
ase ' 1 ' :
Push ( p i l a ) ;
break ;
ase ' 2 ' :
PushGreater ( p i l a ) ;
break ;
ase ' 3 ' :
Top ( p i l a ) ;
break ;
ase ' 4 ' :
Pop ( p i l a ) ;
break ;
ase ' 5 ' :
Svuota ( p i l a ) ;
break ;
ase ' 6 ' :
Count ( p i l a ) ;
break ;
ase ' 7 ' :
Empty ( p i l a ) ;
break ;
ase ' 8 ' :
break ;
default :
out << " S e l t a non
break ;
}
} while ( != ' 8 ' ) ;
return 0 ;

void

v a l i d a . \ n" ;

stampaMenu ( ) {
out << e n d l ;
out << " 1 . Push" << e n d l ;
out << " 2 . PushGreater " << e n d l ;
out << " 3 . Top" << e n d l ;
out << " 4 . Pop" << e n d l ;
out << " 5 . Svuota " << e n d l ;
out << " 6 . Count " << e n d l ;
out << " 7 . Empty" << e n d l ;
out << " 8 . E s i " << e n d l ;
out << e n d l ;
out << " S e l t a : " ;

void

Push ( P i l a& p ) {

109

SP. Soluzioni degli eser izi su pile

TElem e l ;
out << " I n s e r i r e elemento : " ;
i n >> e l ;
p . Push ( e l ) ;

void

PushGreater ( P i l a& p ) {
TElem e l ;
out << " I n s e r i r e elemento : " ;
i n >> e l ;
( p . PushGreater ( e l ) )
out << " Elemento i n s e r i t o . \ n" ;

if
else

out << " Elemento non i n s e r i t o . \ n" ;

void Top ( P i l a& p ) {


if ( ! p . Empty ( ) )
out << " Elemento
else

d i t e s t a : " << p . Top ( ) << e n d l ;

out << " P i l a vuota . " << e n d l ;

void Pop ( P i l a& p ) {


if ( ! p . Empty ( ) )
out << " Elemento
else

d i t e s t a : " << p . Pop ( ) << e n d l ;

out << " P i l a vuota . " << e n d l ;

void
}

Svuota ( P i l a& p ) {
p . Svuota ( ) ;
out << " P i l a s v u o t a t a . \ n" ;

void
}

Count ( P i l a& p ) {
out << "Numero e l e m e n t i : " << p . Count ( ) << e n d l ;

void Empty ( P i l a& p ) {


if ( p . Empty ( ) )
out << " True . " <<
else
}

endl ;

out << " F a l s e . " << e n d l ;

110

Capitolo SC
Soluzioni degli eser izi su ode
SC.1 Coda
Tra ia a pag. 27

#in lude <i o s t r e a m . h>


#in lude <s t d l i b . h>
typedef int TElem ;
stru t Re ord ;
typedef Re ord PRe ;
typedef stru t Re ord {
};

TElem e l ;
PRe s u ;
Re ord ( ) { out << " C o s t r u t t o r e i n v o a t o . \ n" ; }
~Re ord ( ) { out << " D i s t r u t t o r e i n v o a t o . \ n" ; }

lass Coda
private :

PRe head ;
PRe t a i l ;
nelem ;
:
Coda ( ) ;
~Coda ( ) ;

int
publi

void

};

onst TElem&
onst ;
onst ;
onst ;
onst ;

Push (
TElem Top ( )
TElem Pop ( ) ;
TElem Somma ( )
Svuota ( ) ;
Count ( )
Empty ( )

void
int
bool

e );

Coda : : Coda ( ) : head ( 0 ) , t a i l ( 0 ) , nelem ( 0 ) {


}
Coda : : ~ Coda ( ) {
Svuota ( ) ;
111

SC. Soluzioni degli eser izi su ode

112

void

onst
new

Coda : : Push (
TElem& e ) {
// Creo un nuovo elemento n e l l ' heap
PRe temp =
Re ord ;
temp>e l = e ;
temp>s u = 0 ;

// s e ' un elemento d i oda q u e s t o deve puntare a l nuovo elemento


( tail )
t a i l >s u = temp ;

if

// i n o g n i aso l a oda punter a l nuovo elemento


t a i l = temp ;
// s e l a t e s t a non punta ad un elemento , deve puntare a l nuovo elemento :
// l a oda , i o , era vuota a l momento d e l l ' i n s e r i m e n t o
( ! head )
head = temp ;

if

nelem++;

onst

TElem Coda : : Top ( )


( head )
head >e l ;
}

if

return

TElem Coda : : Pop ( ) {


( head ) {
PRe temp = head ;
TElem el_temp = temp>e l ;

if

// head passa a puntare a l l ' elemento s u e s s i v o


head = head >s u ;
// s e non punta a n i e n t e v u o l e d i r e he l a oda onteneva un s o l o elemento
// an he t a i l q u i n d i deve puntare a 0
( ! head )
t a i l = 0;

if

nelem ;
temp ;
el_temp ;

delete
return

onst

TElem Coda : : Somma( )


{
TElem sum = 0 ;
( PRe temp = head ; temp != 0 ; temp = temp>s u )
sum = sum + temp>e l ;

for

return

sum ;

void Coda : : Svuota ( )


while ( head != 0)
}

{
{

PRe tbd = head ;


head = head >s u ;
tbd ;

delete

SC. Soluzioni degli eser izi su ode

head = t a i l = 0 ;
nelem = 0 ;

int Coda : : Count ( ) onst


return nelem ;

bool Coda : : Empty ( ) onst


return ( nelem == 0 ) ;

void stampaMenu ( ) ;
void Push ( Coda& ) ;
void Top ( Coda& ) ;
void Pop ( Coda& ) ;
void Somma( Coda& ) ;
void Svuota ( Coda& ) ;
void Count ( Coda& ) ;
void Empty ( Coda& ) ;
int main ( )
{
har ;
Coda oda ;

do

{
stampaMenu ( ) ;
i n >> ;
in . ignore ( ) ;

swit h ( ) {
ase ' 1 ' :
Push ( oda ) ;
break ;
ase ' 2 ' :
Top ( oda ) ;
break ;
ase ' 3 ' :
Pop ( oda ) ;
break ;
ase ' 4 ' :
Somma( oda ) ;
break ;
ase ' 5 ' :
Svuota ( oda ) ;
break ;
ase ' 6 ' :
Count ( oda ) ;
break ;
ase ' 7 ' :
Empty ( oda ) ;
break ;
ase ' 8 ' :
break ;
default :
out << " S e l t a
break ;
}
} while ( != ' 8 ' ) ;
return 0 ;

non v a l i d a . \ n" ;

113

SC. Soluzioni degli eser izi su ode


}

void

stampaMenu ( ) {
out << e n d l ;
out << " 1 . Push" << e n d l ;
out << " 2 . Top" << e n d l ;
out << " 3 . Pop" << e n d l ;
out << " 4 . Somma" << e n d l ;
out << " 5 . Svuota " << e n d l ;
out << " 6 . Count " << e n d l ;
out << " 7 . Empty" << e n d l ;
out << " 8 . E s i " << e n d l ;
out << e n d l ;
out << " S e l t a : " ;

void
}

Push ( Coda& ) {
TElem e l ;
out << " I n s e r i r e elemento : " ;
i n >> e l ;
. Push ( e l ) ;

void Top ( Coda& ) {


if ( ! . Empty ( ) )
out << " Elemento
else

d i t e s t a : " << . Top ( ) << e n d l ;

out << "Coda vuota . " << e n d l ;

void Pop ( Coda& ) {


if ( ! . Empty ( ) )
out << " Elemento
else

d i t e s t a : " << . Pop ( ) << e n d l ;

out << "Coda vuota . " << e n d l ;

void
}

Somma( Coda& ) {
out << "Somma e l e m e n t i : " << . Somma( ) << e n d l ;

void
}

Svuota ( Coda& ) {
. Svuota ( ) ;
out << "Coda s v u o t a t a . \ n" ;

void
}

Count ( Coda& ) {
out << "Numero e l e m e n t i : " << . Count ( ) << e n d l ;

void Empty ( Coda& ) {


if ( . Empty ( ) )
out << " True . " <<
else
}

endl ;

out << " F a l s e . " << e n d l ;

114

SC. Soluzioni degli eser izi su ode

115

SC.2 Coda on Perdite


Tra ia a pag. 28

#in lude <i o s t r e a m . h>


#in lude <s t d l i b . h>
typedef int TElem ;
stru t Re ord ;
typedef Re ord PRe ;
typedef stru t Re ord {
};

TElem e l ;
PRe s u ;

lass Coda
private :

PRe head ;
PRe t a i l ;

unsigned int p o s t i ;
int nelem ;
publi :
Coda ( unsigned int _posti ) ;
~Coda ( ) ;

bool

};

onst TElem& e ) ;
onst ;
unsigned int n ) ;
onst ;
onst ;

Push (
TElem Top ( )
TElem Pop ( ) ;
TElem Pop (
Svuota ( ) ;
Count ( )
Empty ( )

void
int
bool

Coda : : Coda (
}

unsigned int

_posti ) : head ( 0 ) , t a i l ( 0 ) , p o s t i ( _posti ) , nelem ( 0 ) {

Coda : : ~ Coda ( ) {
Svuota ( ) ;
}

bool
if

onst

Coda : : Push (
TElem& e ) {
( nelem == p o s t i )
;

return false

// Creo un nuovo elemento n e l l ' heap


PRe temp =
Re ord ;
temp>e l = e ;
temp>s u = 0 ;

new

// s e ' un elemento d i oda q u e s t o deve puntare a l nuovo elemento


( tail )
t a i l >s u = temp ;

if

// i n o g n i aso l a oda punter a l nuovo elemento


t a i l = temp ;
// s e l a t e s t a non punta ad un elemento , deve puntare a l nuovo elemento :
// l a oda , i o , era vuota a l momento d e l l ' i n s e r i m e n t o
( ! head )

if

SC. Soluzioni degli eser izi su ode

116

head = temp ;
nelem++;
}

return true ;
onst

TElem Coda : : Top ( )


( head )
head >e l ;
}

if

return

TElem Coda : : Pop ( ) {


( head ) {
PRe temp = head ;
TElem el_temp = temp>e l ;

if

// head passa a puntare a l l ' elemento s u e s s i v o


head = head >s u ;
// s e non punta a n i e n t e v u o l e d i r e he l a oda onteneva un s o l o elemento
// an he t a i l q u i n d i deve puntare a 0
( ! head )
t a i l = 0;

if

nelem ;
temp ;
el_temp ;

delete
return

unsigned int

TElem Coda : : Pop (


( head ) {
TElem e l = Pop ( ) ;

if

n) {

// e s t r a z i o n e d e i r e s t a n t i e l e m e n t i : s i usa i l metodo Pop ( ) ;


(
i = 2 ; ( i <= n ) && head ; i ++)
Pop ( ) ;

for int

return

el ;

void Coda : : Svuota ( )


while ( head != 0)
}

{
{

PRe tbd = head ;


head = head >s u ;
tbd ;

delete

head = t a i l = 0 ;
nelem = 0 ;

int Coda : : Count ( ) onst


return nelem ;

bool Coda : : Empty ( ) onst


return ( nelem == 0 ) ;

SC. Soluzioni degli eser izi su ode

void stampaMenu ( ) ;
void Push ( Coda& ) ;
void Top ( Coda& ) ;
void Pop ( Coda& ) ;
void PopMany( Coda& ) ;
void Svuota ( Coda& ) ;
void Count ( Coda& ) ;
void Empty ( Coda& ) ;
int main ( )
{
har ;
unsigned int i ;
out << " I n s e r i r e i l numero massimo d i e l e m e n t i i n oda : " ;
i n >> i ;
Coda oda ( i ) ;

do

{
stampaMenu ( ) ;
i n >> ;
in . ignore ( ) ;

swit h ( ) {
ase ' 1 ' :
Push ( oda ) ;
break ;
ase ' 2 ' :
Top ( oda ) ;
break ;
ase ' 3 ' :
Pop ( oda ) ;
break ;
ase ' 4 ' :
PopMany( oda ) ;
break ;
ase ' 5 ' :
Svuota ( oda ) ;
break ;
ase ' 6 ' :
Count ( oda ) ;
break ;
ase ' 7 ' :
Empty ( oda ) ;
break ;
ase ' 8 ' :
break ;
default :
out << " S e l t a
break ;
}
} while ( != ' 8 ' ) ;
return 0 ;

void

non v a l i d a . \ n" ;

stampaMenu ( ) {
out << e n d l ;
out << " 1 . Push" << e n d l ;
out << " 2 . Top" << e n d l ;
out << " 3 . Pop" << e n d l ;

117

SC. Soluzioni degli eser izi su ode

out
out
out
out
out
out
out

<<
<<
<<
<<
<<
<<
<<

" 4 . PopMany" << e n d l ;


" 5 . Svuota " << e n d l ;
" 6 . Count " << e n d l ;
" 7 . Empty" << e n d l ;
" 8 . E s i " << e n d l ;
endl ;
" S elta : " ;

void

Push ( Coda& ) {
TElem e l ;
out << " I n s e r i r e elemento : " ;
i n >> e l ;
( . Push ( e l ) )
out << " Elemento i n s e r i t o . \ n" ;

if
else

out << " Elemento NON i n s e r i t o . \ n" ;

void Top ( Coda& ) {


if ( ! . Empty ( ) )
out << " Elemento
else

d i t e s t a : " << . Top ( ) << e n d l ;

out << "Coda vuota . " << e n d l ;

void Pop ( Coda& ) {


if ( ! . Empty ( ) )
out << " Elemento
else

d i t e s t a : " << . Pop ( ) << e n d l ;

out << "Coda vuota . " << e n d l ;

void PopMany( Coda&


int i ;

) {

out << " Quanti e l e m e n t i e s t r a r r e ? " ;


i n >> i ;

if ( ! . Empty ( ) )
out << " Elemento
else

d i t e s t a : " << . Pop ( i ) << e n d l ;

out << "Coda vuota . " << e n d l ;

void
}

Svuota ( Coda& ) {
. Svuota ( ) ;
out << "Coda s v u o t a t a . \ n" ;

void
}

Count ( Coda& ) {
out << "Numero e l e m e n t i : " << . Count ( ) << e n d l ;

void Empty ( Coda& ) {


if ( . Empty ( ) )
out << " True . " <<
else
}

endl ;

out << " F a l s e . " << e n d l ;

118

SC. Soluzioni degli eser izi su ode

119

SC.3 Coda a Priorit


Tra ia a pag. 29

Si vuole una oda in ui gli elementi possano essere liberamente a odati


e siano onnotati da uno tra due possibili livelli di priorit.

Il prelievo di

un elemento dalla oda dovr rispettare, in primis, il livello di priorit e,


nell'ambito degli elementi aventi la stessa priorit, la dis iplina rst-in-rst-

out (FIFO) di una oda.


La tra ia spe i a es lusivamente il omportamento esteriore della
struttura dati, senza denire al un dettaglio di natura implementativa. Per
ottenere una struttura avente il omportamento spe i ato possibile seguire
diverse strade. Di seguito sono riportate al une possibilit.

Appro io 1
La oda a priorit pu essere immaginata formata da una sequenza di elementi ostituita a sua volta da due sotto-sequenze (vedi Figura SC.1):

una prima sotto-sequenza, he parte dalla testa, he omprende gli


elementi a priorit alta;

una su essiva sotto-sequenza, he si estende no alla oda, he omprende gli elementi a priorit bassa.

Una o entrambe queste sotto-sequenze possono in generale essere vuote.


Dal momento he le operazioni di prelievo (Pop) e di inserimento a bassa
priorit (PushLow) orrispondono in questo aso alle normali operazioni usate nel aso di una lassi a oda, l'uni a operazione nuova da implementare
onsiste nell'inserimento in oda di un elemento a priorit alta (PushHigh).
Tale operazione prevede l'aggiunta di un elemento in oda agli elementi a
priorit alta. In quest'otti a risulta utile denire un puntatore aggiuntivo

posizionato sull'ultimo degli elementi a priorit alta. Tale nuovo puntatore


punter alla oda degli elementi ad alta priorit, oppure varr zero in aso
di assenza di tali elementi.

File PriorityQueue.h

typedef int TElem ;


stru t Re ord ;
typedef Re ord PRe ;
lass P r i o r i t y Q u e u e {
private :

SC. Soluzioni degli eser izi su ode

t
Figura SC.1:

120

Una sequenza di elementi formata da due sotto-sequenze

onse utive

PRe head ;
PRe t a i l ; // p u n t a t o r e a l l a oda
PRe t a i l _ h ; // p u n t a t o r e a l l a oda d e l l a s o t t o s e q u e n z a ad a l t a p r i o r i t
Push (
TElem& e ) ; // l a s s i o Push i n oda
:
PriorityQueue ( ) ;
~P r i o r i t y Q u e u e ( ) ;

void
publi

};

onst

void PushLow ( onst TElem& e ) ;


void PushHigh ( onst TElem& e ) ;
TElem Pop ( ) ;
void C l e a r ( ) ;
bool Empty ( ) onst ;
File PriorityQueue. pp

#in lude " P r i o r i t y Q u e u e . h"


typedef stru t Re ord {
};

TElem e l ;
PRe s u ;

P r i o r i t y Q u e u e : : P r i o r i t y Q u e u e ( ) : head ( 0 ) , t a i l ( 0 ) , t a i l _ h ( 0 ) {}
PriorityQueue : :~ PriorityQueue () {
Clear ( ) ;
}

void

onst

P r i o r i t y Q u e u e : : Push (
TElem& e ) { // l a s s i o Push i n oda
// Creo un nuovo elemento n e l l ' heap
PRe temp =
Re ord ;
temp>e l = e ;
temp>s u = 0 ;

new

// s e ' un elemento d i oda q u e s t o deve puntare a l nuovo elemento


( tail )
t a i l >s u = temp ;

if

// i n o g n i aso l a oda punter a l nuovo elemento


t a i l = temp ;
// s e l a t e s t a non punta ad un elemento , deve puntare a l nuovo elemento :
// l a s t r u t t u r a , i o , era vuota a l momento d e l l ' i n s e r i m e n t o
( ! head )
head = temp ;

if

SC. Soluzioni degli eser izi su ode

void
}

121

onst

P r i o r i t y Q u e u e : : PushLow (
TElem& e ) {
Push ( e ) ; // s i r i d u e ad un l a s s i o i n s e r i m e n t o i n oda

void
if

P r i o r i t y Q u e u e : : PushHigh (
( ! tail_h ) {

onst

TElem& e ) {

//non i sono e l e m e n t i ad a l t a p r i o r i t : a g g i u n t a i n t e s t a
( ! head ) // l a oda vuota ?
Push ( e ) ; // i n s e r i s o on Push ( )
{
PRe temp =
Re ord ;
temp>e l = e ;
temp>s u = head ;
head = temp ;
}

if
else

new

t a i l _ h = head ; // l ' elemento i n s e r i t o i n t e s t a : t a i l _ h deve p u n t a r v i


}

else

{
// i n s e r i s o
PRe temp =
Re ord ;
temp>e l = e ;
temp>s u = tail_h >s u ;
tail_h >s u = temp ;

new

t a i l _ h = temp ; // a g g i o r n o i l p u n t a t o r e t a i l _ h

// a g g i o r n o t a i l s e l ' elemento a g g i u n t o i n u l t i m a p o s i z i o n e
( ! tail_h >s u )
t a i l = tail_h ;

if

TElem P r i o r i t y Q u e u e : : Pop ( ) {
( head ) {
PRe temp = head ;
TElem el_temp = temp>e l ;

if

if

( head == t a i l _ h ) // ho p r e l e v a t o l ' uni o elemento a p r i o r i t a l t a ?


tail_h = 0;
// a l l o r a non e ne sono p i

// head passa a puntare a l l ' elemento s u e s s i v o


head = head >s u ;
// s e non punta a n i e n t e v u o l e d i r e he l a oda onteneva un s o l o elemento ;
// an he t a i l q u i n d i deve puntare a 0
( ! head ) {
t a i l = 0;
tail_h = 0;
}

if

delete
return

temp ;
el_temp ;

void P r i o r i t y Q u e u e : : C l e a r ( )
while ( head != 0) {
PRe tbd = head ;

SC. Soluzioni degli eser izi su ode

122

CODA A PRIORIT

SOTTO-CODA AD
ALTA PRIORIT

SOTTO-CODA A
BASSA PRIORIT

Figura SC.2: Coda a priorit formata da due lassi he ode aan ate

}
}

head = head >s u ;


tbd ;

delete

head = t a i l = t a i l _ h = 0 ;

bool P r i o r i t y Q u e u e : : Empty ( ) onst


return ! head ;

Appro io 2
La oda a priorit pu essere immaginata omposta di due ode sempli i
aan ate (vedi Figura SC.2).
bassa priorit. Il metodo
Il metodo

Pop()

Il metodo

PushHigh(),

PushLow()

a oda nella oda a

vi eversa, in quella ad alta priorit.

restituis e il primo elemento ad alta priorit se esiste; in

aso ontrario restituis e il primo elemento a bassa priorit.


Servendosi del me anismo dell'aggregazione stretta tra lassi, le due o-

Coda (vedi EC.1). Denendo tali


PriorityQueue esse non risulteran-

de aan ate risultano istanze della lasse


istanze ome membri privati della lasse

no visibili dall'esterno della struttura (information hiding ), la quale ontinuer ad apparire ai suoi utenti ome un'uni a oda dotata dei me anismi
di priorit ri hiesti.

#in lude " oda . h"


lass P r i o r i t y Q u e u e
private :

Coda oda_l ;
Coda oda_h ;

onst P r i o r i t y Q u e u e& ) ; // i n i b i s e
operator=( onst P r i o r i t y Q u e u e& ) ;

PriorityQueue (
P r i o r i t y Q u e u e&
:

publi

la opia . . .
// . . e l ' a s s e g n a z i o n e

SC. Soluzioni degli eser izi su ode

123

PriorityQueue ( ) ;

};

void PushLow ( onst TElem& e ) ;


void PushHigh ( onst TElem& e ) ;
TElem Pop ( ) ;
void C l e a r ( ) ;
bool Empty ( ) onst ;

#in lude " p r i o r i t y q u e u e . h"


void P r i o r i t y Q u e u e : : PushLow ( onst
}

oda_l . Push ( e ) ;

void
}

P r i o r i t y Q u e u e : : PushHigh (
oda_h . Push ( e ) ;

onst

TElem& e ) {

TElem& e ) {

TElem P r i o r i t y Q u e u e : : Pop ( ) {
( ! oda_h . Empty ( ) )
oda_h . Pop ( ) ;
}

if
return
else
return

oda_l . Pop ( ) ;

void
}

PriorityQueue : : Clear () {
oda_h . Svuota ( ) ;
oda_l . Svuota ( ) ;

bool P r i o r i t y Q u e u e : : Empty ( ) onst {


return ( oda_h . Empty ( ) && oda_l . Empty ( ) ) ;

Appro io 3
La oda a priorit pu essere una normale oda in ui i re ord, disposti
se ondo l'ordine di inserimento, vengono eti hettati on la loro priorit
di Figura SC.3).

PushLow(),

il metodo

In questo aso sia il metodo

PushHigh()

(ve-

he il metodo

previa opportuna eti hettatura, eettuano un'aggiunta in oda.

Pop()

in questo aso a prendersi ari o della restituzione del

giusto elemento. Tale operazione viene eettuata s orrendo tutta la struttura alla ri er a del primo elemento ad alta priorit e restituendolo dopo
averlo eliminato dalla oda. In assenza di un elemento ad alta priorit viene
restituito l'eventuale elemento di testa.
Tale implementazione, pur prestandosi a diverse ottimizzazioni, non risulta parti olarmente e iente, ri hiedendo un i lo di ri er a per ogni operazione

Pop()

1 Questo

eettuata. La sua implementazione non qui riportata.

possibile previa denizione di un'opportuna stru t he ontenga un TElem


ed un bool indi ante la relativa priorit.

SC. Soluzioni degli eser izi su ode

124

el

el

el

el

el

el

el

el

el

Figura SC.3: Sequenza di elementi eti hettati

SC.4 PopMinMax
Tra ia a pag. 30

// Metodo p r i v a t o
// I l metodo s e g u e n t e e s t r a e n e l e m e n t i e ne r e s t i t u i s e i l minimo ed i l massimo
Coda : : _PopMinMax(
n , TElem& min , TElem& max) {
min = max = Pop ( ) ; // Assegno min e max a l l ' elemento d i t e s t a

void

unsigned int

unsigned int

i = 1;
// o n f r o n t o on g l i a l t r i n1 e l e m e n t i s e g u e n t i : n1 i t e r a z i o n i
// ( s e l a oda non s i s v u o t a prima )
( ( i < n ) && ! Empty ( ) ) {
TElem e l = Pop ( ) ;
( e l < min )
min = e l ;
( e l > max)
max = e l ;
i ++;
}

while
if
if

// Metodi p u b b l i i
// I l metodo s e g u e n t e hiama _PopMinMax ( ) e r e s t i t u i s e i l massimo
TElem Coda : : PopMax (
n) {
TElem min , max ;
_PopMinMax( n , min , max ) ;
max ;
}

unsigned int

return

// I l metodo s e g u e n t e hiama _PopMinMax ( ) e r e s t i t u i s e i l minimo


TElem Coda : : PopMin (
n) {
TElem min , max ;
_PopMinMax( n , min , max ) ;
min ;
}

unsigned int

return

Capitolo SX
Soluzioni degli altri eser izi
SX.1 A umulatore
Tra ia a pag. 32

#in lude <i o s t r e a m>


using namespa e s t d ;
lass A umulatore {
private :
float a ;
publi :
A umulatore ( ) { Reset ( ) ; } ;
void Add( float v a l ) { a += v a l ;
void Reset ( ) { a = 0 ; } ;
float GetValue ( ) onst { return
};

int

};
a ; };

main ( )

A umulatore a ;
f;
h ;

float
har
out
out
out
out

do

<<
<<
<<
<<

" 'a '


"'r '
"'s '
" 'e '

add \n" ;
r e s e t \n" ;
show\n" ;
e x i t \n" ;

{
i n >> h ;
( h ) {
'a ' :
out << " I n s e r t v a l u e : " ;
i n >> f ;
a . Add( f ) ;
out << " Value added . \ n" ;
;
'r ':
a . Reset ( ) ;
out << " Reset . \ n" ;

swit h
ase

break
ase

125

SX. Soluzioni degli altri eser izi

break ;
ase ' s ' :
out << "The
break ;
ase ' e ' :
break ;
default :

v a l u e i s " << a . GetValue ( ) << e n d l ;

out << " I n v a l i d ommand . \ n" ;

while ( h
return 0 ;
}

126

!= ' e ' ) ;

In questo eser izio i metodi della lasse

A umulatore vengono imple lass. Questa te ni a par-

mentati direttamente nell'ambito del ostrutto

ti olarmente onveniente nel aso di metodi molto sempli i ( ome questi ostituiti da una sola riga), ed equivalente a rendere i metodi

inline attraverso

l'appro io lassi o alla stesura dei metodi di una lasse e l'uso della keyword

inline.

SX.2 Cifratore
Tra ia a pag. 32

#in lude <i o s t r e a m . h>


#in lude <s t d l i b . h>
lass C i f r a t o r e {
private :
int h i a v e ;
har C i f r a C a r a t t e r e ( har , bool
publi :
C i f r a t o r e ( int ) ;
void C i f r a ( har s t r ) onst ;
void D e i f r a ( har s t r ) onst ;

onst ;

ifra )

};

Cifratore : : Cifratore (
}

int

) : hiave ( ) {

har C i f r a t o r e : : C i f r a C a r a t t e r e ( har
if ( i f r a )
return + h i a v e ;
else
return h i a v e ;

bool

void C i f r a t o r e : : C i f r a ( har
while ( s t r ) {

str )

s t r = C i f r a C a r a t t e r e ( str ,

void

s t r ++;

Cifratore : : De ifra (

har

onst {
true ) ;

str )

onst

ifra )

onst

SX. Soluzioni degli altri eser izi

while

( s t r ) {
s t r = C i f r a C a r a t t e r e ( str ,

s t r ++;

127

false ) ;

int main ( )
har s t r [ 1 0 0 ;
int h i a v e ;

out << " I n s e r i s i l a p a r o l a da i f r a r e : " ;


i n >> s t r ;
out << " I n s e r i s i l a h i a v e d i i f r a t u r a : " ;
i n >> h i a v e ;
Cifratore ( hiave ) ;
out << " S t r i n g a : " << s t r << e n d l ;
. Cifra ( str ) ;
out << " C i f r a t u r a : " << s t r << e n d l ;
. De ifra ( str ) ;
out << " D e i f r a t u r a : " << s t r << e n d l ;

system ( "PAUSE" ) ;
0;

return

SX.3 Lista Della Spesa


Tra ia a pag. 33

#in lude <i o s t r e a m>


using namespa e s t d ;
onst int MAX_CHARS = 2 0 ;
typedef har Nome [MAX_CHARS ;
typedef float Quantita ;
stru t A r t i o l o {
};

Nome n ;
Quantita q ;

stru t Re ord ;
typedef Re ord
stru t Re ord {
};

PRe ;

Arti olo art ;


PRe s u ;

lass L i s t a D e l l a S p e s a {
private :
PRe f i r s t ;
bool R i e r a ( onst Nome n , PRe & p ) onst ;
bool _Elimina ( PRe & p , onst Nome n ) ;
bool S t r i n g h e U g u a l i ( onst har s1 , onst har

s2 )

onst

SX. Soluzioni degli altri eser izi

return

128

( str mp ( s1 , s2 ) == 0 ) ;

// i n i b i s e l a o p i a mediante o s t r u t t o r e
ListaDellaSpesa (
L i s t a D e l l a S p e s a &) { } ;
// i n i b i s e l a o p i a mediante a s s e g n a z i o n e
= (
L i s t a D e l l a S p e s a &) { } ;
:
ListaDellaSpesa ( ) ;
~ListaDellaSpesa ( ) ;

onst
void operator onst
publi

};

Quantita Aggiungi ( onst Nome n ,


bool Elimina ( onst Nome n ) ;
Quantita GetQuantita ( onst Nome
void Svuota ( ) ;
void Stampa ( ) onst ;

Quantita q ) ;
n)

onst ;

ListaDellaSpesa : : ListaDellaSpesa ( ) : f i r s t (0) {


}
ListaDellaSpesa ::~ ListaDellaSpesa () {
Svuota ( ) ;
}

bool

onst

onst

ListaDellaSpesa : : Ri er a (
Nome n , PRe & p )
{
// Questo metodo e r a l ' a r t i o l o a v e n t e i l nome s p e i f i a t o e r e s t i t u i s e :
// t r u e o f a l s e , a se onda he l ' a r t i o l o s i a s t a t o t r o v a t o o meno ;
// i l p u n t a t o r e a l l ' u l t i m o r e o r d v i s i t a t o .
( first ) {
p = first ;
( S t r i n g h e U g u a l i ( p>a r t . n , n ) )
;
{
( p>s u ) {
p = p>s u ;
( S t r i n g h e U g u a l i ( p>a r t . n , n ) )
;
}
}
}

if

if
return true
else
while
if
return true

return false ;

bool
if

onst

L i s t a D e l l a S p e s a : : _Elimina ( PRe & p ,


Nome n ) {
// metodo r i o r s i v o d i e l i m i n a z i o n e d i un elemento d a l l a l i s t a
(p) {
( S t r i n g h e U g u a l i ( p>a r t . n , n ) ) {
PRe tbd = p ;
p = tbd >s u ;
tbd ;
;
}
}
}

if

delete
return true
else
return _Elimina ( p>su ,

n);

return false ;

Quantita L i s t a D e l l a S p e s a : : Aggiungi (

onst

Nome n , Quantita q ) {

SX. Soluzioni degli altri eser izi

if

129

(! first ) {
first =
Re ord ;
f i r s t >s u = 0 ;
s t r p y ( f i r s t >a r t . n , n ) ;
f i r s t >a r t . q = q ;
q;

new

return
else {

PRe p ;

if
}

( R i e r a ( n , p ) ) { // e s i s t e n e l l a l i s t a un elemento a v e n t e i l nome n?
// t r o v a t o => ora p punta a l l ' elemento a v e n t e nome n
p>a r t . q += q ;

else

{
// non t r o v a t o => ora p punta a l l ' u l t i m o elemento d e l l a l i s t a
Re ord ;
p>s u =
p = p>s u ;
s t r p y ( p>a r t . n , n ) ;
p>a r t . q = q ;
p>s u = 0 ;

return

new

p>a r t . q ;

bool L i s t a D e l l a S p e s a : : Elimina ( onst


return _Elimina ( f i r s t , n ) ;

Nome n ) {

Quantita L i s t a D e l l a S p e s a : : GetQuantita (
PRe p ;
( Ri er a (n , p ))
p>a r t . q ;
}

if
return
else
return

void
if

onst

Nome n )

0;

L i s t a D e l l a S p e s a : : Svuota ( ) {
( first ) {
PRe tbd = f i r s t ;
PRe p ;

while ( tbd ) {
p = tbd >s u ;
delete tbd ;
}

tbd = p ;

}
f i r s t = 0;

void L i s t a D e l l a S p e s a : : Stampa ( ) onst


PRe p = f i r s t ;
while ( p ) {
}

void

out << p>a r t . n << " : " << p>a r t . q << e n d l ;


p = p>s u ;

stampa_menu( ) {

onst

SX. Soluzioni degli altri eser izi

out
out
out
out
out
out
out

<<
<<
<<
<<
<<
<<
<<

" 1:
" 2:
" 3:
" 4:
" 5:
" 6:
" 7:

Aggiungi a r t i o l o . \ n" ;
Elimina a r t i o l o . \ n" ;
Quantita ' a r t i o l o . \ n" ;
Svuota l i s t a . \ n" ;
Stampa l i s t a . \ n" ;
E s e g u i t e s t v e l o e . \ n" ;
E s i . \ n" ;

void Aggiungi ( L i s t a D e l l a S p e s a & l ) ;


void Elimina ( L i s t a D e l l a S p e s a& l ) ;
void GetQuantita ( L i s t a D e l l a S p e s a & l ) ;
void Svuota ( L i s t a D e l l a S p e s a& l ) ;
void Stampa ( L i s t a D e l l a S p e s a& l ) ;
void T e s t V e l o e ( L i s t a D e l l a S p e s a& l ) ;
int main ( )

ListaDellaSpesa l ;

int s e l t a ;
do {

stampa_menu ( ) ;
i n >> s e l t a ;
( s elta ) {
1:
Aggiungi ( l ) ;
;
2:
Elimina ( l ) ;
;
3:
GetQuantita ( l ) ;
;
4:
Svuota ( l ) ;
;
5:
Stampa ( l ) ;
;
6:
TestVelo e ( l ) ;
;
7:
;
:
out << " S e l t a non v a l i d a . \ n" ;
;
}
}
( s e l t a != 7 ) ;

swit h
ase
break
ase
break
ase
break
ase
break
ase
break
ase
break
ase
break
default
break
while
return 0 ;

void

Aggiungi ( L i s t a D e l l a S p e s a & l ) {
Nome n ;
Quantita q , qq ;
out << "Nome a r t i o l o : " ;
i n >> n ;
out << " Quantita ' : " ;
i n >> q ;
qq = l . Aggiungi ( n , q ) ;

130

SX. Soluzioni degli altri eser izi

131

out << "Ora l a q u a n t i t a ' e ' " << qq << e n d l ;

void

Elimina ( L i s t a D e l l a S p e s a& l ) {
Nome n ;
out << "Nome a r t i o l o : " ;
i n >> n ;

if ( l . Elimina ( n ) )
out << " A r t i o l o
else

e l i m i n a t o . " << e n d l ;

out << " A r t i o l o non e l i m i n a t o . " << e n d l ;

void

GetQuantita ( L i s t a D e l l a S p e s a & l ) {
Nome n ;
Quantita q ;
out << "Nome a r t i o l o : " ;
i n >> n ;
q = l . GetQuantita ( n ) ;
out << "La q u a n t i t a ' e ' " << q << e n d l ;

void
}

Svuota ( L i s t a D e l l a S p e s a& l ) {
l . Svuota ( ) ;
out << " L i s t a s v u o t a t a . " << e n d l ;

void
}

Stampa ( L i s t a D e l l a S p e s a& l ) {
out << " L i s t a : " << e n d l ;
l . Stampa ( ) ;

void

T e s t V e l o e ( L i s t a D e l l a S p e s a& l ) {
l . Svuota ( ) ;
l . Aggiungi ( "Pane " , 1 ) ;
l . Aggiungi ( " L a t t e " , 1 . 5 ) ;
l . Aggiungi ( " Zu hero " , 1 ) ;
l . Aggiungi ( " P r o s i u t t o " , 0 . 3 ) ;
l . Stampa ( ) ;
out << " L a t t e : " << l . Aggiungi ( " L a t t e " , 0 . 5 ) << e n d l ;
l . Elimina ( "Pane " ) ;
l . Elimina ( " Zu hero " ) ;
l . Elimina ( " P r o s i u t t o " ) ;
out << " L a t t e : " << l . Aggiungi ( " L a t t e " , 0 . 5 ) << e n d l ;
l . Svuota ( ) ;
l . Stampa ( ) ;

SX.4 Predittore di Temperatura


Tra ia a pag. 34

Il metodo

EstimateTemp()

deve eettuare un'estrapolazione lineare della

temperatura basandosi sui dati delle ultime due letture omuni ate.
formula da utilizzare la seguente:

La

SX. Soluzioni degli altri eser izi

132

T2 T1
(t t1 ) + T1 ;
T =
t2 t1
dove

la stima della temperatura all'istante

t; T1 , T2 , t1

t2

sono

le ultime due letture della temperatura ed i relativi due istanti di lettura,


rispettivamente.

N.B.: Variando l'implementazione del metodo EstimateTemp() (ed eventualmente la


sezione private della lasse) diviene possibile operare stime pi a urate della temperatura; si potrebbe per esempio pensare di operare estrapolazioni di ordine superiore al primo.
Per giunta i, non alterando l'interfa ia della lasse, non avrebbe al una riper ussione
sui moduli utenti del predittore.

#in lude <i o s t r e a m>


#in lude <s t d l i b . h>
using namespa e s t d ;
typedef int Time ;
typedef float Temp ;
lass TempPredi tor {
private :
Time
Time
Temp
Temp

time1 ;
time2 ;
temp1 ;
temp2 ;

publi :
TempPredi tor ( Time time , Temp temp ) ;
void SetTemp ( Time time , Temp temp ) ;
Temp EstimateTemp ( Time time ) onst ;
};

TempPredi tor : : TempPredi tor ( Time time , Temp temp ) :


time1 ( time 1) , time2 ( time ) , temp1 ( temp ) , temp2 ( temp ) {
// Impostare i n q u e s t o modo l e t e m p e r a t u r e ed i tempi s i g n i f i a imporre he l e
// u l t i m e _due_ l e t t u r e d e l l a temperatura hanno f o r n i t o un r i s u l t a t o p a r i a temp
// e su q u e s t e u l t i m e due l e t t u r e b i s o g n a e s t r a p o l a r e l a stima .
}

void
}

TempPredi tor : : SetTemp ( Time time , Temp temp ) {


time1 = time2 ; // " s p o s t a " l ' u l t i m a l e t t u r a n e l l a penultima
temp1 = temp2 ;
time2 = time ; // a g g i o r n a l ' u l t i m a l e t t u r a on i d a t i p r o v e n i e n t i d a l l ' u t e n t e
temp2 = temp ;

onst

Temp TempPredi tor : : EstimateTemp ( Time time )


{
( ( temp2temp1 ) / ( time2 time1 ) ) ( time time1 ) + temp1 ;
}

return

int

main ( )

out << " L e t t u r a : a l l ' i s t a n t e 0 : l a temperatura v a l e 14\ n" ;

SX. Soluzioni degli altri eser izi

133

// Posso o s t r u i r e i l p r e d i t t o r e on q u e s t i d a t i .
TempPredi tor tp ( 0 , 1 4 ) ;
out << " Stima : l a temperatura a l l ' i s t a n t e 10 s a r a ' "
<< tp . EstimateTemp ( 1 0 ) << e n d l ;
out << " Stima : l a temperatura a l l ' i s t a n t e 20 s a r a ' "
<< tp . EstimateTemp ( 2 0 ) << e n d l ;
out << " L e t t u r a : a l l ' i s t a n t e 5 : l a temperatura v a l e 16\ n" ;

//Comuni o l a l e t t u r a a l p r e d i t t o r e
tp . SetTemp ( 5 , 1 6 ) ;
out << " Stima : l a temperatura a l l ' i s t a n t e 10 s a r a ' "
<< tp . EstimateTemp ( 1 0 ) << e n d l ;
out << " Stima : l a temperatura a l l ' i s t a n t e 12 s a r a ' "
<< tp . EstimateTemp ( 1 2 ) << e n d l ;
out << " L e t t u r a : a l l ' i s t a n t e 1 0 : l a temperatura v a l e 16\ n" ;

//Comuni o l a l e t t u r a a l p r e d i t t o r e
tp . SetTemp ( 1 0 , 1 6 ) ;
out << " Stima : l a temperatura a l l ' i s t a n t e 15 s a r a ' "
<< tp . EstimateTemp ( 1 5 ) << e n d l ;
out << " Stima : l a temperatura a l l ' i s t a n t e 20 s a r a ' "
<< tp . EstimateTemp ( 2 0 ) << e n d l ;

system ( "PAUSE" ) ;
0;

return

SX.5 Contenitore
Tra ia a pag. 35

#in lude <i o s t r e a m>


using namespa e s t d ;
onst int NMAX = 5 0 ;
typedef har Nome [NMAX ;
typedef int Peso ; // s i t r a t t i
stru t Oggetto {
};

Nome n ;
Peso p ;

stru t C e l l a ;
typedef C e l l a
stru t C e l l a {
};

PCella ;

Oggetto elem ;
PCella s u ;

lass

Contenitore {

i l peso ome v a l o r e i n t e r o ( p . e s . grammi )

SX. Soluzioni degli altri eser izi

134

private :

PCella f i r s t ;
Peso a p a i t a ;
Peso somma_pesi ;
nelem ;
:
C o n t e n i t o r e ( Peso max ) ;
~Contenitore ( ) ;

unsigned int
publi
bool
void

har

n , Peso p ) ;
Inseris i (
Svuota ( ) ;
Peso PesoComplessivo ( )
;
Peso PesoResiduo ( )
;
NumElem ( )
;
Stampa ( )
;

unsigned int
void
onst

};

onst
onst
onst

C o n t e n i t o r e : : C o n t e n i t o r e ( Peso max ) : f i r s t ( 0 ) , a p a i t a (max) ,


somma_pesi ( 0 ) , nelem ( 0 ) {
}
Contenitore : : ~ Contenitore () {
Svuota ( ) ;
}

bool
if

har

Contenitore : : I n s e r i s i (
n , Peso p ) {
( p <= a p a i t a somma_pesi ) {
PCella =
Cella ;
s t r p y ( >elem . n , n ) ;
>elem . p = p ;
>s u = f i r s t ;
first = ;

new

somma_pesi = somma_pesi + p ; // i l o n t e n i t o r e ora p i p e s a n t e d i p . . .


nelem++; // . . . e ' un elemento i n p i .
}
}

return true ;

return false ;

void C o n t e n i t o r e : : Svuota ( )
while ( f i r s t ) {
}

PCella tbd = f i r s t ;
f i r s t = f i r s t >s u ;
tbd ;

delete

somma_pesi = 0 ;
nelem = 0 ;

Peso C o n t e n i t o r e : : PesoComplessivo ( )
somma_pesi ;
}

return

Peso C o n t e n i t o r e : : PesoResiduo ( )
a p a i t a somma_pesi ;
}

return

unsigned int

onst

onst

C o n t e n i t o r e : : NumElem ( )

onst

SX. Soluzioni degli altri eser izi

return

nelem ;

void C o n t e n i t o r e : : Stampa ( ) onst


PCella p = f i r s t ;
while ( p ) {
}

void
void
void
void
void
void
void

out << p>elem . n << " , " << p>elem . p << e n d l ;


p = p>s u ;

I n s e r i s i ( Contenitore& ) ;
Svuota ( C o n t e n i t o r e & ) ;
PesoComplessivo ( C o n t e n i t o r e & ) ;
PesoResiduo ( C o n t e n i t o r e & ) ;
NumeroElementi ( C o n t e n i t o r e & ) ;
Stampa ( C o n t e n i t o r e & ) ;

stampa_menu( ) {
out << " 1 : I n s e r i s i . \ n" ;
out << " 2 : Svuota . \ n" ;
out << " 3 : Peso Complessivo . \ n" ;
out << " 4 : Peso Residuo . \ n" ;
out << " 5 : Numero Elementi . \ n" ;
out << " 6 : Stampa . \ n" ;
out << " 7 : E s i . \ n" ;

int

135

main ( )

Peso p ;
out << " I n s e r i s i peso MAX o n t e n i t o r e : " ;
i n >> p ;
Contenitore (p ) ;

int s e l t a ;
do {

stampa_menu ( ) ;
i n >> s e l t a ;
( s elta ) {
1:
Inseris i ( );
;
2:
Svuota ( ) ;
;
3:
PesoComplessivo ( ) ;
;
4:
PesoResiduo ( ) ;
;
5:
NumeroElementi ( ) ;
;
6:
Stampa ( ) ;
;
7:
;
:
out << " S e l t a non v a l i d a . \ n" ;

swit h
ase
break
ase
break
ase
break
ase
break
ase
break
ase
break
ase
break
default

SX. Soluzioni degli altri eser izi

break ;
} while ( s e l t a
return 0 ;
}

136

!= 7 ) ;

void I n s e r i s i ( C o n t e n i t o r e &
har n [NMAX ;

) {

Peso p ;

out << " I n s e r i s i nome elemento : " ;


i n >> n ;
out << " I n s e r i s i peso elemento : " ;
i n >> p ;
( . I n s e r i s i (n , p ))
out << " Elemento i n s e r i t o . \ n" ;

if
else

out << " Elemento NON i n s e r i t o . \ n" ;

void
}

Svuota ( C o n t e n i t o r e & ) {
. Svuota ( ) ;
out << " C o n t e n i t o r e s v u o t a t o . \ n" ;

void
}

PesoComplessivo ( C o n t e n i t o r e & ) {
out << " I l peso o m p l e s s i v o e ' : " << . PesoComplessivo ( ) << e n d l ;

void
}

PesoResiduo ( C o n t e n i t o r e & ) {
out << " I l peso r e s i d u o e ' : " << . PesoResiduo ( ) << e n d l ;

void
}

NumeroElementi ( C o n t e n i t o r e & ) {
out << "N. Elem : " << . NumElem ( ) << e n d l ;

void
}

Stampa ( C o n t e n i t o r e & ) {
out << " I l o n t e n u t o d e l o n t e n i t o r e e ' : \ n" ;
. Stampa ( ) ;
out << e n d l ;

SX.6 Lista Prenotazioni


Tra ia a pag. 37

#in lude <i o s t r e a m>


using namespa e s t d ;
onst int MAX_CHARS = 2 0 ;
typedef int M a t r i o l a ;
typedef har Nome [ 3 0 ;
stru t P r e n o t a z i o n e {
M a t r i o l a mat ;

SX. Soluzioni degli altri eser izi

};

137

Nome nom ;

lass L i s t a P r e n o t a z i o n i {
private :
P r e n o t a z i o n e pv ; // p u n t a t o r e a v e t t o r e p r e n o t a z i o n i
int p o s t i ; //numero d i p o s t i d i s p o n i b i l i
int nelem ; // riempimento d e l v e t t o r e
int R i e r a ( M a t r i o l a m) onst ;
publi :
L i s t a P r e n o t a z i o n i ( int n ) ;

dinami amente a l l o a t o

~ListaPrenotazioni ( ) ;

};

bool Prenota ( M a t r i o l a m, Nome n ) ;


bool E l i m i n a P r e n o t a z i o n e ( M a t r i o l a m) ;
int G e t P o s t i D i s p o n i b i l i ( ) onst ;
bool E s i s t e P r e n o t a z i o n e ( M a t r i o l a m) onst ;
void Svuota ( ) ;
void Stampa ( ) ;

ListaPrenotazioni : : ListaPrenotazioni (
pv =
Prenotazione [ posti ;
}

new

int

n ) : p o s t i ( n ) , nelem ( 0 ) {

ListaPrenotazioni ::~ ListaPrenotazioni () {


[ pv ;
}

delete

int L i s t a P r e n o t a z i o n i : : R i e r a ( M a t r i o l a m) onst
for ( int i = 0 ; i < nelem ; i ++)
if ( pv [ i . mat == m)
return i ;
return 1;

bool
if

L i s t a P r e n o t a z i o n i : : Prenota ( M a t r i o l a m, Nome n ) {
( ( G e t P o s t i D i s p o n i b i l i ( ) > 0) && ( ! E s i s t e P r e n o t a z i o n e (m) ) ) {
pv [ nelem . mat = m;
s t r p y ( pv [ nelem . nom , n ) ;
nelem++;

}
}

return true ;

return false ;

bool L i s t a P r e n o t a z i o n i : : E l i m i n a P r e n o t a z i o n e ( M a t r i o l a m)
int i = R i e r a (m) ;
if ( i >= 0) {
for ( int j = i ; j < nelem 1 ; j ++)
pv [ j = pv [ j + 1 ;

nelem ;
}

return true ;

SX. Soluzioni degli altri eser izi

138

return false ;

int L i s t a P r e n o t a z i o n i : : G e t P o s t i D i s p o n i b i l i ( ) onst
return p o s t i nelem ;

bool L i s t a P r e n o t a z i o n i : : E s i s t e P r e n o t a z i o n e ( M a t r i o l a m) onst
return ( R i e r a (m) >= 0 ) ;
}

void
}

L i s t a P r e n o t a z i o n i : : Svuota ( ) {
nelem = 0 ;

void L i s t a P r e n o t a z i o n i : : Stampa ( ) {
for ( int i = 0 ; i < nelem ; i ++)

out << pv [ i . mat << " : " << pv [ i . nom << e n d l ;

out << e n d l ;

void

stampa_menu( ) {
out << " 1 : Prenota . \ n" ;
out << " 2 : Elimina p r e n o t a z i o n e . \ n" ;
out << " 3 : P o s t i d i s p o n i b i l i . \ n" ;
out << " 4 : E s i s t e P r e n o t a z i o n e . \ n" ;
out << " 5 : Svuota . \ n" ;
out << " 6 : Stampa . \ n" ;
out << " 7 : E s i . \ n" ;

void Prenota ( L i s t a P r e n o t a z i o n i& l ) ;


void Elimina ( L i s t a P r e n o t a z i o n i& l ) ;
void G e t P o s t i D i s p o n i b i l i ( L i s t a P r e n o t a z i o n i& l ) ;
void E s i s t e P r e n o t a z i o n e ( L i s t a P r e n o t a z i o n i& l ) ;
void Svuota ( L i s t a P r e n o t a z i o n i& l ) ;
void Stampa ( L i s t a P r e n o t a z i o n i& l ) ;
int main ( )
{
int n ;

out << " I n s e r i r e i l numero d i p o s t i d i s p o n i b i l i : " ;


i n >> n ;
ListaPrenotazioni l (n ) ;

int s e l t a ;
do {

stampa_menu ( ) ;
i n >> s e l t a ;
( s elta ) {
1:
Prenota ( l ) ;
;
2:
Elimina ( l ) ;
;
3:
GetPostiDisponibili ( l );
;
4:

swit h
ase
break
ase
break
ase
break
ase

SX. Soluzioni degli altri eser izi


EsistePrenotazione ( l ) ;

break ;
ase 5 :
Svuota ( l ) ;
break ;
ase 6 :
Stampa ( l ) ;
break ;
ase 7 :
break ;
default :
out << " S e l t a non
break ;
}
} while ( s e l t a != 7 ) ;
return 0 ;

v a l i d a . \ n" ;

void

Prenota ( L i s t a P r e n o t a z i o n i& l ) {
M a t r i o l a m;
Nome n ;
out << " I n s e r i s i M a t r i o l a : " ;
i n >> m;
out << " I n s e r i s i nome : " ;
i n >> n ;

if ( l . Prenota (m, n ) )
out << " P r e n o t a z i o n e
else

e f f e t t u a t a . \ n" ;

out << " P r e n o t a z i o n e non e f f e t t u a t a . \ n" ;

void

Elimina ( L i s t a P r e n o t a z i o n i& l ) {
M a t r i o l a m;

out << " I n s e r i s i M a t r i o l a : " ;


i n >> m;

if ( l . E l i m i n a P r e n o t a z i o n e (m) )
out << " P r e n o t a z i o n e e l i m i n a t a . \ n" ;
else

out << " P r e n o t a z i o n e non e l i m i n a t a . \ n" ;

void
}

G e t P o s t i D i s p o n i b i l i ( L i s t a P r e n o t a z i o n i& l ) {
out << " I p o s t i d i s p o n i b i l i sono : " ;
out << l . G e t P o s t i D i s p o n i b i l i ( ) << e n d l ;

void

E s i s t e P r e n o t a z i o n e ( L i s t a P r e n o t a z i o n i& l ) {
M a t r i o l a m;

out << " I n s e r i s i M a t r i o l a : " ;


i n >> m;

if ( l . E s i s t e P r e n o t a z i o n e (m) )
out << " P r e n o t a z i o n e e s i s t e n t e . \ n" ;
else
}

out << " P r e n o t a z i o n e non e s i s t e n t e . \ n" ;

139

SX. Soluzioni degli altri eser izi

140

void
}

Svuota ( L i s t a P r e n o t a z i o n i& l ) {
l . Svuota ( ) ;
out << " L i s t a s v u o t a t a . \ n" ;

void
}

Stampa ( L i s t a P r e n o t a z i o n i& l ) {
l . Stampa ( ) ;

SX.7 Classi a
Tra ia a pag. 38

#in lude <i o s t r e a m>


#in lude <s t r i n g . h>
using namespa e s t d ;
onst int NMAX = 5 0 ;
typedef har Nome [NMAX ;
stru t Re ord ;
typedef Re ord PRe ;
typedef stru t {
Nome n ;
unsigned int p u n t e g g i o ;
} Squadra ;

typedef Squadra
stru t Re ord {
};

TElem e l ;
PRe s u ;

TElem ;

// S i n g o l o elemento ( e l l a ) d e l l a s t r u t t u r a

lass C l a s s i f i a {
private :
PRe f i r s t ;
unsigned int nelem ;
C l a s s i f i a ( onst C l a s s i f i a &); // i n i b i s e l a o p i a mediante o s t r u t t o r e
void operator= ( onst C l a s s i f i a &); // i n i b i s e l ' a s s e g n a z i o n e
unsigned int Elimina ( onst Nome& n ) ;
void I n s e r i m e n t o O r d i n a t o ( onst Nome& n , unsigned int p u n t i ) ;
publi :
Classifi a ();
~Classifi a ();

};

unsigned int Aggiungi ( onst


void Svuota ( ) ;
void Stampa ( ) onst ;
unsigned int Count ( ) onst ;

Nome& n ,

unsigned int

C l a s s i f i a : : C l a s s i f i a ( ) : f i r s t ( 0 ) , nelem ( 0 ) {

punti ) ;

SX. Soluzioni degli altri eser izi

141

}
Classifi a ::~ Classifi a () {
Svuota ( ) ;
}

unsigned int

onst

C l a s s i f i a : : Elimina (
Nome& n ) {
// Questo metodo e l i m i n a d a l l a s t r u t t u r a un e v e n t u a l e elemento a v e n t e nome p a r i
// ad n . In aso d i e s i s t e n z a ne r e s t i t u i s e i l p u n t e g g i o , a l t r i m e n t i
// r e s t i t u i s e 0 .

//E ' i l primo elemento ? ( Caso p a r t i o l a r e )


( f i r s t && ( str mp ( f i r s t >e l . n , n ) == 0 ) ) {
PRe tbd = f i r s t ;
f i r s t = f i r s t >s u ;
p u n t i = tbd >e l . p u n t e g g i o ;
tbd ;
nelem ;
punti ;
}

if

unsigned int
delete
return

//E ' un elemento s u e s s i v o a l primo ?


PRe p = f i r s t ;
( p && p>s u ) {
// o n t r o l l o s e i l s u e s s i v o d i p deve e s s e r e e l i m i n a t o
( str mp ( p>su >e l . n , n ) == 0) {
PRe tbd = p>s u ;
p>s u = tbd >s u ;
p u n t i = tbd >e l . p u n t e g g i o ;
tbd ;
nelem ;
punti ;
}

while
if

unsigned int
delete
return

p = p>s u ;

// Elemento non t r o v a t o
0;

return

void

onst

unsigned int

C l a s s i f i a : : InserimentoOrdinato (
Nome& n ,
punti ) {
// Questo metodo e f f e t t u a un i n s e r i m e n t o o r d i n a t o n e l l a s t r u t t u r a , i n b a s e a l
// ampo p u n t e g g i o . S i pro ede a t t r a v e r s o i s e g u e n t i p a s s i :
// s e l a l i s t a vuota s i i n s e r i s e l ' elemento e s i e s e ;
// s i o n t r o l l a s e i n s e r i r e i n t e s t a : s e s , s i i n s e r i s e e s i e s e ;
// s i e r a i l punto d i i n s e r i m e n t o a t t r a v e r s o una v i s i t a , s i i n s e r i s e
//
( e v e n t u a l m e n t e i n oda ) e s i e s e .

// In o g n i aso a l l o o un nuovo r e o r d
PRe nuovo =
Re ord ;
s t r p y ( nuovo>e l . n , n ) ;
nuovo>e l . p u n t e g g i o = p u n t i ;
nelem++;

new

if

( ! f i r s t ) { // Se l a l i s t a vuota
f i r s t = nuovo ; // I n s e r i s o a l l a t e s t a
nuovo>s u = 0 ;
}
{
// Se i l p u n t e g g i o d e l l a nuova squadra maggiore d e l l a t e s t a
( p u n t i >= f i r s t >e l . p u n t e g g i o ) {
nuovo>s u = f i r s t ; // I n s e r i s o i n t e s t a

else
if

SX. Soluzioni degli altri eser izi

f i r s t = nuovo ;

else { //Devo e r a r e i l punto d i i n s e r z i o n e


PRe p = f i r s t ;
while ( p && p>s u ) {
//Devo i n s e r i r e dopo l ' elemento p u n t a t o da
if ( p u n t i >= p>su >e l . p u n t e g g i o ) {

p?

nuovo>s u = p>s u ;
p>s u = nuovo ;
;

return

142

p = p>s u ;

// Se sono qui , non ho an ora i n s e r i t o : i n s e r i m . i n oda , a l l a q u a l e punta p


p>s u = nuovo ;
nuovo>s u = 0 ;

unsigned int C l a s s i f i a : : Aggiungi ( onst Nome& n , unsigned int p u n t i ) {


unsigned int p = Elimina ( n ) ; // Elimina d a l l a l i s t a l ' elemento ( s e e s i s t e )
I n s e r i m e n t o O r d i n a t o ( n , p u n t i + p ) ; //Lo ( re ) i n s e r i s e a l p o s t o g i u s t o
}

return

p u n t i + p ; // R e s t i t u i s e i l g i u s t o p u n t e g g i o

void C l a s s i f i a : : Svuota ( )
while ( f i r s t ) {

PRe tbd = f i r s t ;
f i r s t = f i r s t >s u ;
tbd ;

delete

}
nelem = 0 ;

void C l a s s i f i a : : Stampa ( ) onst


PRe p = f i r s t ;
while ( p ) {
}

out << p>e l . n << " : " << p>e l . p u n t e g g i o << e n d l ;


p = p>s u ;

unsigned int C l a s s i f i a : : Count ( ) onst


return nelem ;
}

void

stampa_menu( ) {
out << " 1 : I n s e r i s i . \ n" ;
out << " 2 : Svuota . \ n" ;
out << " 3 : Stampa . \ n" ;
out << " 4 : Count . \ n" ;
out << " 5 : E s i . \ n" ;

void
void
void
void

Aggiungi ( C l a s s i f i a& l ) ;
Svuota ( C l a s s i f i a& l ) ;
Stampa ( C l a s s i f i a& l ) ;
Count ( C l a s s i f i a& l ) ;

SX. Soluzioni degli altri eser izi

int

143

main ( )

Classifi a l ;

int s e l t a ;
do {

stampa_menu ( ) ;
i n >> s e l t a ;
( s elta ) {
1:
Aggiungi ( l ) ;
;
2:
Svuota ( l ) ;
;
3:
Stampa ( l ) ;
;
4:
Count ( l ) ;
;
5:
;
:
out << " S e l t a non v a l i d a . \ n" ;
;
}
}
( s e l t a != 5 ) ;

swit h
ase
break
ase
break
ase
break
ase
break
ase
break
default
break
while
return 0 ;

void Aggiungi ( C l a s s i f i a&


Nome n ;
unsigned int p u n t i ;

l) {

out << " I n s e r i s i nome : " ;


i n >> n ;
out << " I n s e r i s i p u n t i : " ;
i n >> p u n t i ;
out << "La squadra " << n << " ora ha p u n t i : " << l . Aggiungi ( n , p u n t i ) << " . \ n" ;

void
}

Svuota ( C l a s s i f i a& l ) {
l . Svuota ( ) ;
out << " C l a s s i f i a s v u o t a t a . \ n" ;

void
}

Stampa ( C l a s s i f i a& l ) {
l . Stampa ( ) ;
out << e n d l ;

void
}

Count ( C l a s s i f i a& l ) {
out << " I l numero d i e l e m e n t i e ' : " << l . Count ( ) << e n d l ;

SX. Soluzioni degli altri eser izi

144

SX.8 Agenzia Matrimoniale


Tra ia a pag. 39

#in lude <i o s t r e a m>


using namespa e s t d ;
onst int NMAX = 5 0 ;
typedef har Nome [NMAX ;
stru t p e r s o n a ;
typedef stru t Persona {
Nome n ;
bool mas hio ;
};

Persona o n i u g e ;

typedef Persona
stru t Re ord ;
typedef Re ord
stru t Re ord {
};

//Nome Persona

TElem e l ;
PRe s u ;

TElem ;
PRe ;
// S i n g o l o elemento ( e l l a ) d e l l a s t r u t t u r a

lass AgenziaMatrimoniale
private :

PRe f i r s t ;

AgenziaMatrimoniale ( onst AgenziaMatrimoniale &); // i n i b i s e l a o p i a da


void operator= ( onst AgenziaMatrimoniale &); // i n i b i s e l ' a s s e g n a z i o n e
PRe Cer a (Nome n ) onst ;
publi :

ostruttore

AgenziaMatrimoniale ( ) ;
~AgenziaMatrimoniale ( ) ;

};

bool AggiungiPersona (Nome n , bool s e s s o ) ;


bool Sposa (Nome n1 , Nome n2 ) ;
bool Coniugato (Nome n , bool& o n i u g a t o ) onst ;
unsigned int NumeroSposi ( ) onst ;
unsigned int NumeroCoppie ( ) onst ;
void Svuota ( ) ;
void Stampa ( ) onst ;

AgenziaMatrimoniale : : AgenziaMatrimoniale ( ) : f i r s t ( 0 ) {
}
AgenziaMatrimoniale : : ~ AgenziaMatrimoniale ( ) {
Svuota ( ) ;
}

onst

PRe AgenziaMatrimoniale : : Cer a (Nome n )


{
// Cer a n e l l a l i s t a l a persona a v e n t e i l nome s p e i f i a t o
// R e s t i t u i s e i l p u n t a t o r e a l l a o r r i s p o n d e n t e e l l a s e e s i s t e , 0 a l t r i m e n t i .
PRe p = f i r s t ;
(p) {
( str mp ( p>e l . n , n ) == 0)

while
if

SX. Soluzioni degli altri eser izi

145

return

}
}

p;
p = p>s u ;

return

bool
if

0;

AgenziaMatrimoniale : : AggiungiPersona (Nome n ,


( Cer a ( n ) )
;

return false

bool

mas hio ) {

// I n s e r i m e n t o i n t e s t a
PRe p =
Re ord ;
s t r p y ( p>e l . n , n ) ;
p>e l . mas hio = mas hio ;
p>e l . o n i u g e = 0 ;
p>s u = f i r s t ;
first = p;

new

return true ;

bool

AgenziaMatrimoniale : : Sposa (Nome n1 , Nome n2 ) {


PRe p1 = Cer a ( n1 ) ;
// s e i l primo nome non s t a t o t r o v a t o r e s t i t u i s e f a l s e
( ! p1 )
;

if

return false

PRe p2 = Cer a ( n2 ) ;
// s e i l se ondo nome non s t a t o t r o v a t o r e s t i t u i s e f a l s e
( ! p2 )
;

if

return false

// s e i due nomi sono u g u a l i r e s t i t u i s e f a l s e


( p1 == p2 )
;

if

return false

// s e i l s e s s o u g u a l e r e s t i t u i s e f a l s e
( p1>e l . mas hio == p2>e l . mas hio )
;

if

return false

// s e una d e l l e due persone g i s p o s a t a r e s t i t u i s e f a l s e


( p1>e l . o n i u g e | | p2>e l . o n i u g e )
;

if

return false

p1>e l . o n i u g e = &p2>e l ;
p2>e l . o n i u g e = &p1>e l ;
}

return true ;

bool

AgenziaMatrimoniale : : Coniugato (Nome n ,


PRe p = Cer a ( n ) ;

if

bool&

oniugato )

( ! p)

return false ;

o n i u g a t o = ( p>e l . o n i u g e != 0 ) ;

return true ;

unsigned int

AgenziaMatrimoniale : : NumeroSposi ( )

onst

onst

SX. Soluzioni degli altri eser izi

146

unsigned int

ount = 0 ;
PRe p = f i r s t ;

while ( p ) {
if ( p>e l . o n i u g e
}
}

ount++;
p = p>s u ;

return

!= 0)

ount ;

unsigned int AgenziaMatrimoniale : : NumeroCoppie ( ) onst


return NumeroSposi ( ) / 2 ;
}

void AgenziaMatrimoniale : : Svuota ( )


while ( f i r s t ) {
}

PRe tbd = f i r s t ;
f i r s t = f i r s t >s u ;
tbd ;

delete

void AgenziaMatrimoniale : : Stampa ( ) onst


PRe p = f i r s t ;
while ( p ) {
out << p>e l . n << " ( " ;
if ( p>e l . mas hio )
out << 'M' ;
else

out << 'F ' ;


out << " ) ; " ;

if

( p>e l . o n i u g e )
out << " o n i u g e : " << p>e l . oniuge >n << " . " ;

out << e n d l ;

p = p>s u ;

void

stampa_menu( ) {
out << " 1 : AggiungiPersona . \ n" ;
out << " 2 : Sposa . \ n" ;
out << " 3 : Coniugato . \ n" ;
out << " 4 : NumeroSposi . \ n" ;
out << " 5 : NumeroCoppie . \ n" ;
out << " 6 : Svuota . \ n" ;
out << " 7 : Stampa . \ n" ;
out << " 8 : E s i . \ n" ;

void
void
void
void
void
void
void

AggiungiPersona ( AgenziaMatrimoniale& am ) ;
Sposa ( AgenziaMatrimoniale& am ) ;
Coniugato ( AgenziaMatrimoniale& am ) ;
NumeroSposi ( AgenziaMatrimoniale& am ) ;
NumeroCoppie( AgenziaMatrimoniale& am ) ;
Svuota ( AgenziaMatrimoniale& am ) ;
Stampa ( AgenziaMatrimoniale& am ) ;

SX. Soluzioni degli altri eser izi

int

147

main ( )

AgenziaMatrimoniale am;

int s e l t a ;
do {

stampa_menu ( ) ;
i n >> s e l t a ;
( s elta ) {
1:
AggiungiPersona (am ) ;
;
2:
Sposa (am ) ;
;
3:
Coniugato (am ) ;
;
4:
NumeroSposi (am ) ;
;
5:
NumeroCoppie(am ) ;
;
6:
Svuota (am ) ;
;
7:
Stampa (am ) ;
;
8:
;
:
out << " S e l t a non v a l i d a . \ n" ;
;
}
}
( s e l t a != 8 ) ;

swit h
ase
break
ase
break
ase
break
ase
break
ase
break
ase
break
ase
break
ase
break
default
break
while
return 0 ;

void

AggiungiPersona ( AgenziaMatrimoniale& am) {


Nome n ;
out << " S p e i f i a r e i l nome : " ;
i n >> n ;
sesso ;
{
out << " S p e i f i a r e i l s e s s o (M, F ) : " ;
i n >> s e s s o ;
}
( ( s e s s o != 'M' ) && ( s e s s o != 'm' ) && ( s e s s o != 'F ' ) && ( s e s s o != ' f ' ) ) ;

har
do

while
bool mas hio = ( s e s s o == 'M' | | s e s s o
if (am. AggiungiPersona ( n , mas hio ) )
out << " Persona a g g i u n t a . \ n" ;
else
out << " Persona non a g g i u n t a . \ n" ;

void

Sposa ( AgenziaMatrimoniale& am) {


Nome n1 , n2 ;
out << " I n s e r i r e primo nome : " ;

== 'm' ) ;

SX. Soluzioni degli altri eser izi

148

i n >> n1 ;
out << " I n s e r i r e se ondo nome : " ;
i n >> n2 ;

if (am. Sposa ( n1 , n2 ) )
out << " Matrimonio
else

r e g i s t r a t o . \ n" ;

out << " Matrimonio non r e g i s t r a t o . \ n" ;

void Coniugato ( AgenziaMatrimoniale& am)


Nome n ;
bool o n i u g a t o ;

out << " I n s e r i s i i l nome : " ;


i n >> n ;
( ! am. Coniugato ( n , o n i u g a t o ) )
out << " Persona non e s i s t e n t e . \ n" ;

if
else
if ( o n i u g a t o )
out << n << "
else

ha o n i u g e . \ n" ;

out << n << " non ha o n i u g e . \ n" ;

void
}

NumeroSposi ( AgenziaMatrimoniale& am) {


out << " I l numero s p o s i p a r i a " << am. NumeroSposi ( ) << e n d l ;

void
}

NumeroCoppie( AgenziaMatrimoniale& am) {


out << " I l numero o p p i e p a r i a " << am. NumeroCoppie ( ) << e n d l ;

void
}

Svuota ( AgenziaMatrimoniale& am) {


am. Svuota ( ) ;
out << " AgenziaMatrimoniale s v u o t a t a . \ n" ;

void
}

Stampa ( AgenziaMatrimoniale& am) {


am. Stampa ( ) ;
out << e n d l ;

SX.9 Par o Pattini


Tra ia a pag. 41

La struttura dati pu essere realizzata ome una lista dinami a sempli emente ollegata in ui ogni elemento rappresenta lo stato di tutti i pattini di una
data taglia. La generi a ella della struttura ontiene dunque:

taglia dei pattini;

numero totale di pattini della taglia data;

numero totale di pattini disponibili della taglia data.

SX. Soluzioni degli altri eser izi


first

44

149

43

42

Numero pattini
disponibili

Taglia dei pattini


Numero pattini
complessivo

Figura SX.1: La struttura he implementa il par o pattini.

A titolo esempli ativo si immagini he il par o pattini disponga di un


paio di pattini della taglia 44, di un paio della taglia 43 e di due paia della
taglia 42. Se uno delle due paia di pattini della taglia 42 risulta ttato, lo
stato della struttura mostrato in Figura SX.1.
Si noti ome la struttura ammetta una gestione di tipo tabellare, dal
momento he la taglia dei pattini risulta essere uni a per ogni ella, e quindi
assimilabile ad una hiave.
Di seguito si riporta il listato.

#in lude <i o s t r e a m>


using namespa e s t d ;
typedef unsigned int T a g l i a ;
stru t P a t t i n i {
Taglia t a g l i a ;
unsigned int t o t a l i ;
unsigned int d i s p o n i b i l i ;
};

stru t Re ord ;
typedef Re ord PRe ;
typedef stru t Re ord
};

Pattini pattini ;
PRe s u ;

lass P a r o P a t t i n i {
private :
PRe f i r s t ;
unsigned int t o t ;

PRe GetRe ordByTaglia ( T a g l i a t )

onst
operator onst

onst ;

Par oPattini (
P a r o P a t t i n i &); // i n i b i s e l a o p i a mediatne o s t r u t t o r e
P a r o P a t t i n i&
=(
P a r o P a t t i n i &); // i n i b i s e l ' a s s e g n a z i o n e
:
Par oPattini ( ) ;
~Par oPattini ( ) ;
AggiungiPattini ( Taglia t ) ;
Svuota ( ) ;
NumeroTotPattini ( )
;
Fitta ( Taglia t ) ;

publi

void
void
unsigned int
bool

onst

SX. Soluzioni degli altri eser izi

};

unsigned int D i s p o n i b i l i t a ( T a g l i a
unsigned int NumeroPattini ( T a g l i a
bool R e s t i t u z i o n e ( T a g l i a t ) ;
void Stampa ( ) onst ;

150

t)
t)

onst ;
onst ;

P a r o P a t t i n i : : P a r o P a t t i n i ( ) : f i r s t ( 0 ) , t o t ( 0 ) {}
Par oPattini ::~ Par oPattini () {
Svuota ( ) ;
}

onst

PRe P a r o P a t t i n i : : GetRe ordByTaglia ( T a g l i a t )


{
// Questo metodo p e r m e t t e l a g e s t i o n e d e l l a l i s t a ome t a b e l l a .
// R e s t i t u i s e i l p u n t a t o r e a l l a e l l a o n t e n e n t e i p a t t i n i d e l l a t a g l i a r i h i e s t a ,
// oppure 0 s e t a l e e l l a non n e l l a l i s t a .
PRe p = f i r s t ;

while ( p ) {
if ( p>p a t t i n i . t a g l i a == t ) // t r o v a t o ?
return p ; // r e s t i t u i s e i l p u n t a t o r e
else

p = p>s u ; // a l t r i m e n t i avanza d i una e l l a

}
}

alla ella della lista

return

0 ; // non t r o v a t o .

void

Par oPattini : : AggiungiPattini ( Taglia t ) {


PRe p = GetRe ordByTaglia ( t ) ;

if
}

(p) {
p>p a t t i n i . t o t a l i ++;
p>p a t t i n i . d i s p o n i b i l i ++;

else

}
}

{
PRe p =
p>p a t t i n i
p>p a t t i n i
p>p a t t i n i
p>s u =
first = p;

new

Re ord ;
. taglia = t ;
. t o t a li = 1;
. disp on ibili = 1;
first ;

t o t ++;

void P a r o P a t t i n i : : Svuota ( )
while ( f i r s t ) {
}
}

PRe tbd = f i r s t ;
f i r s t = f i r s t >s u ;
tbd ;

delete

tot = 0;

unsigned int P a r o P a t t i n i : : NumeroTotPattini ( ) onst


return t o t ;
}

SX. Soluzioni degli altri eser izi

151

bool

Par oPattini : : Fitta ( Taglia t ) {


PRe p = GetRe ordByTaglia ( t ) ;

// i sono p a t t i n i d e l l a t a g l i a s p e i f i a t a , e s e s , e ne sono d i d i s p o n i b i l i ?
( p && ( p>p a t t i n i . d i s p o n i b i l i > 0 ) ) {
p>p a t t i n i . d i s p o n i b i l i ; // de rementa l a d i s p o n i b i l i t
;
}

if

return true
else
return false ;

unsigned int

Par oPattini : : D i s p o n ib il i t a ( Taglia t )


PRe p = GetRe ordByTaglia ( t ) ;

if ( p )
return
else
return

onst

0;

P a r o P a t t i n i : : NumeroPattini ( T a g l i a t )
PRe p = GetRe ordByTaglia ( t ) ;

p>p a t t i n i . d i s p o n i b i l i ;

unsigned int
if ( p )
return
else
return

onst

p>p a t t i n i . t o t a l i ;
0;

bool

Par oPattini : : Restituzione ( Taglia t ) {


PRe p = GetRe ordByTaglia ( t ) ;

// i sono p a t t i n i d e l l a t a g l i a s p e i f i a t a , e s e s , e ne sono d i f i t t a t i ?
( p && ( p>p a t t i n i . d i s p o n i b i l i < p>p a t t i n i . t o t a l i ) ) {
p>p a t t i n i . d i s p o n i b i l i ++;
;
}

if

return true
else
return false ;

void

P a r o P a t t i n i : : Stampa ( )
PRe p = f i r s t ;

onst

while

void
void
void
void
void
void
void
void

(p) {
out << " T a g l i a " << p>p a t t i n i . t a g l i a << " : " ;
out << " T o t a l e : " << p>p a t t i n i . t o t a l i << " " ;
out << " F i t t a t i : " << p>p a t t i n i . t o t a l i p>p a t t i n i . d i s p o n i b i l i << " . \ n" ;
p = p>s u ;

A g g i u n g i P a t t i n i ( P a r o P a t t i n i& p ) ;
Svuota ( P a r o P a t t i n i& p ) ;
NumeroTotPattini ( P a r o P a t t i n i& p ) ;
F i t t a ( P a r o P a t t i n i& p ) ;
D i s p o n i b i l i t a ( P a r o P a t t i n i& p ) ;
NumeroPattini ( P a r o P a t t i n i& p ) ;
R e s t i t u z i o n e ( P a r o P a t t i n i& p ) ;
Stampa ( P a r o P a t t i n i& p ) ;

SX. Soluzioni degli altri eser izi

void

stampa_menu( ) {
out << " \n" ;
out << " 1 : A g g i u n g i P a t t i n i . \ n" ;
out << " 2 : Svuota . \ n" ;
out << " 3 : NumeroTotPattini . \ n" ;
out << " 4 : F i t t a . \ n" ;
out << " 5 : D i s p o n i b i l i t a . \ n" ;
out << " 6 : NumeroPattini . \ n" ;
out << " 7 : R e s t i t u z i o n e . \ n" ;
out << " 8 : Stampa . \ n" ;
out << " 9 : E s i . \ n" ;
out << " S e l t a : " ;

int

main ( )

P a r o P a t t i n i par o ;

int s e l t a ;
do {

stampa_menu ( ) ;
i n >> s e l t a ;
( s elta ) {
1:
A g g i u n g i P a t t i n i ( par o ) ;
;
2:
Svuota ( par o ) ;
;
3:
NumeroTotPattini ( par o ) ;
;
4:
F i t t a ( par o ) ;
;
5:
D i s p o n i b i l i t a ( par o ) ;
;
6:
NumeroPattini ( par o ) ;
;
7:
R e s t i t u z i o n e ( par o ) ;
;
8:
Stampa ( par o ) ;
;
9:
;
:
out << " S e l t a non v a l i d a . \ n" ;
;
}
}
( s e l t a != 9 ) ;

swit h
ase
break
ase
break
ase
break
ase
break
ase
break
ase
break
ase
break
ase
break
ase
break
default
break
while
return 0 ;

void

A g g i u n g i P a t t i n i ( P a r o P a t t i n i& p ) {
Taglia t ;

out << " I n s e r i r e l a t a g l i a : " ;

152

SX. Soluzioni degli altri eser izi

153

i n >> t ;
p . AggiungiPattini ( t ) ;
out << " P a t t i n i a g g i u n t i a l par o . \ n" ;

void
}

Svuota ( P a r o P a t t i n i& p ) {
p . Svuota ( ) ;
out << " Par o s v u o t a t o . \ n" ;

void
}

NumeroTotPattini ( P a r o P a t t i n i& p ) {
out << " I l par o p a t t i n i o n t i e n e " << p . NumeroTotPattini ( ) <<
" p a i a d i p a t t i n i i n t o t a l e . \ n" ;

void

F i t t a ( P a r o P a t t i n i& p ) {
Taglia t ;

out << " I n s e r i r e l a t a g l i a : " ;


i n >> t ;
(p . Fitta ( t ))
out << " P a t t i n i f i t t a t i . \ n" ;

if
else

out << " P a t t i n i non d i s p o n i b i l i . \ n" ;

void

D i s p o n i b i l i t a ( P a r o P a t t i n i& p ) {
Taglia t ;

out << " I n s e r i r e l a t a g l i a : " ;


i n >> t ;
out << " D i s p o n i b i l i t a ' t a g l i a " << t << " : " << p . D i s p o n i b i l i t a ( t ) << e n d l ;

void

NumeroPattini ( P a r o P a t t i n i& p ) {
Taglia t ;

out << " I n s e r i r e l a t a g l i a : " ;


i n >> t ;
out << " I l par o o n t i e n e " << p . NumeroPattini ( t ) <<
" p a i a d i p a t t i n i d i t a g l i a " << t << " . \ n" ;

void

R e s t i t u z i o n e ( P a r o P a t t i n i& p ) {
Taglia t ;

out << " I n s e r i r e l a t a g l i a : " ;


i n >> t ;
(p . Restituzione ( t ))
out << " P a t t i n i r e s t i t u i t i . \ n" ;

if
else

out << " E r r o r e . P a t t i n i non f i t t a t i . \ n" ;

void
}

Stampa ( P a r o P a t t i n i& p ) {
p . Stampa ( ) ;

SX. Soluzioni degli altri eser izi

154

SX.10 Timer
Tra ia a pag. 42

#in lude <i o s t r e a m>


#in lude <time . h>
using namespa e s t d ;
typedef int Time ;
lass Timer {
private :
Time startTime ;
Time stopTime ;
:
Timer ( ) ;
start ();
stop ( ) ;
reset ();
Time getTime ( )

publi
void
void
void
};

onst ;

Timer : : Timer ( ) {
reset ();
}

void
}

Timer : : s t a r t ( ) {
startTime = time ( 0 ) ;
stopTime = 0 ;

void
}

Timer : : s t o p ( ) {
stopTime = time ( 0 ) ;

void
}

Timer : : r e s e t ( ) {
startTime = 0 ;
stopTime = 0 ;

onst

Time Timer : : getTime ( )


{
( startTime == 0) // i l timer i n s t a t o d i r e s e t ?
0;

if

if ( stopTime == 0) // i l timer i n
return time ( 0 ) startTime ; // s
else
return stopTime startTime ; // no

int

return

main ( )

Timer t ;
h ;

har
out
out
out
out
out

<<
<<
<<
<<
<<

"'s '
" 'x '
"'r '
" 'p '
" 'e '

s t a r t \n" ;
s t o p \n" ;
r e s e t \n" ;
show t i m e r \n" ;
e x i t \n" ;

moto?

SX. Soluzioni degli altri eser izi

do

155

{
i n >> h ;
( h ) {
's ':
t . start ();
out << " Timer s t a r t e d . \ n" ;
;
'x ' :
t . stop ( ) ;
out << " Timer stopped . \ n" ;
;
'r ':
t . reset ();
out << " Timer r e s e t . \ n" ;
;
'p ' :
out << " Timer shows : " << t . getTime ( ) << e n d l ;
;
'e ' :
;
:
out << " I n v a l i d ommand . \ n" ;
}
}
( h != ' e ' ) ;

swit h
ase

break
ase

break
ase

break
ase
break
ase
break
default

while
return 0 ;

SX.11 Timer Avanzato


Tra ia a pag. 44

Il primo dei requisiti aggiuntivi imposti dalla tra ia suggeris e intuitivamente he il timer una sorta di a umulatore he tiene memoria della durata
omplessiva degli intervalli di tempo ronometrati no ad un erto istante.
Infatti l'ese uzione di un nuovo onteggio fornis e un ontributo he va a
sommarsi a tutti gli eventuali ontributi pre edenti.
Ai ni dello svolgimento di questo eser izio, il valore orrente del ronometro pu essere pertanto onsiderato ome la omposizione di due ontributi:

la somma di tutti gli intervalli di tempo ronometrati nel passato, io


ompresi tra un segnale di START ed uno di STOP;

l'eventuale ontributo del onteggio orrente, se il timer attivo.

dunque possibile pensare al timer ome una lasse dotata di due membri
privati:

storedTime:

ontiene la somma di tutti i onteggi passati gi terminati;

questo membro va aggiornato al termine di ogni onteggio;

SX. Soluzioni degli altri eser izi


startTime:

156

ontiene l'istante di inizio dell'eventuale onteggio in orso; vale

0 se il timer inattivo.
In questo modo, all'arrivo del messaggio GETTIME, su iente restituire

storedTime, aggiungendo eventualmente la dierenza


e l'istante startTime, se startTime diverso da zero

il valore del membro


tra l'istante attuale

( io se ' un onteggio in orso).


Dal momento he spesso sorge la ne essit di valutare se ' un onteggio
in orso oppure no, in questa implementazione lo svolgimento di tale servizio
stato in apsulato nell'opportuno metodo privato

bool isRunning() onst;

#in lude <i o s t r e a m>


#in lude <time . h>
using namespa e s t d ;
typedef int Time ;
lass Timer {
private :
Time storedTime ;
Time startTime ;
isRunning ( )
:
Timer ( ) ;
start ();
stop ( ) ;
reset ();
Time getTime ( )

bool
publi
void
void
void
};

onst { return

( startTime != 0 ) ; } ;

onst ;

Timer : : Timer ( ) {
reset ();
}

void
if
}

void
if
}

Timer : : s t a r t ( ) {
( ! isRunning ( ) )
startTime = time ( 0 ) ;
Timer : : s t o p ( ) {
( isRunning ( ) ) {
storedTime += time ( 0 ) startTime ; // a umula i l tempo d e l o n t e g g i o i n o r s o
startTime = 0 ; // ferma i l o n t e g g i o

void
}

Timer : : r e s e t ( ) {
storedTime = 0 ;
startTime = 0 ;

Time Timer : : getTime ( )

onst

SX. Soluzioni degli altri eser izi

157

Time t = storedTime ;

if
}

return

int

( isRunning ( ) )
t += time ( 0 ) startTime ; // a g g i u n g e i l o n t r i b u t o d e l o n t e g g i o i n o r s o
t;

main ( )

Timer t ;
h ;

har
out
out
out
out
out

do

<<
<<
<<
<<
<<

"'s '
" 'x '
"'r '
" 'p '
" 'e '

s t a r t \n" ;
s t o p \n" ;
r e s e t \n" ;
show t i m e r \n" ;
e x i t \n" ;

{
i n >> h ;
( h ) {
's ':
t . start ();
out << " Timer s t a r t e d . \ n" ;
;
'x ' :
t . stop ( ) ;
out << " Timer stopped . \ n" ;
;
'r ':
t . reset ();
out << " Timer r e s e t . \ n" ;
;
'p ' :
out << " Timer shows : " << t . getTime ( ) << e n d l ;
;
'e ' :
;
:
out << " I n v a l i d ommand . \ n" ;
}
}
( h != ' e ' ) ;

swit h
ase

break
ase

break
ase

break
ase
break
ase
break
default

while
return 0 ;

SX.12 Votazioni
Tra ia a pag. 44

#in lude <i o s t r e a m>


using namespa e s t d ;
onst int NMAX = 5 0 ;
typedef har Nome [NMAX ;
typedef unsigned int Codi e ;

//un p a r t i t o per s e m p l i i t i d e n t i f i a t o

SX. Soluzioni degli altri eser izi

158

// da un o d i e d i t i p o i n t e r o .

stru t Oggetto
Codi e i d ;
unsigned int
};

stru t C e l l a ;
typedef C e l l a
stru t C e l l a {
};

{
voti ;

PCella ;

Oggetto elem ;
PCella s u ;

lass V o t a z i o n i {
private :
PCella f i r s t ;
unsigned int numVoti ;
PCella C e r a P a r t i t o ( Codi e
publi :

id )

onst ;

Votazioni ( ) ;
~Votazioni ( ) ;

unsigned int AggiungiVoto ( Codi e i d ) ;


void Svuota ( ) ;
unsigned int G e t V o t i P a r t i t o ( Codi e i d ) onst ;
unsigned int GetNumeroVoti ( ) onst ;
void G e t S i t u a z i o n e ( ) onst ;

};

V o t a z i o n i : : V o t a z i o n i ( ) : f i r s t ( 0 ) , numVoti ( 0 ) {
}
Votazioni ::~ Votazioni () {
Svuota ( ) ;
}

onst

PCella V o t a z i o n i : : C e r a P a r t i t o ( Codi e i d )
{
//La s t r u t t u r a g e s t i b i l e on metodo t a b e l l a r e : i n f a t t i i l o d i e
// p a r t i t o r a p p r e s e n t a una h i a v e per l a t a b e l l a d e i v o t i .
// Questo metodo r e s t i t u i s e i l p u n t a t o r e a l l a e l l a a v e n t e i d p a r i a q u e l l o
// s p e i f i a t o i n i n g r e s s o , 0 a l t r i m e n t i .
PCella p = f i r s t ;
trovato =
;

bool
false
while ( ( p ) && ! t r o v a t o )
if ( p>elem . i d == i d )
t r o v a t o = true ;
else
}

p = p>s u ;

return

p ; // s e t r o v a t o vero , p punta a l l a e l l a r i e r a t a , a l t r i m . p z e r o

unsigned int

V o t a z i o n i : : AggiungiVoto ( Codi e i d ) {
numVoti++; // in remento i l numero d i v o t i o m p l e s s i v i
PCella p = C e r a P a r t i t o ( i d ) ;

if

(p) {
p>elem . v o t i ++;

SX. Soluzioni degli altri eser izi

return
else {

159

p>elem . v o t i ;

new

PCella p =
Cella ;
p>elem . i d = i d ;
p>elem . v o t i = 1 ;
p>s u = f i r s t ;
first = p;
1;

return

void V o t a z i o n i : : Svuota ( )
while ( f i r s t ) {

PCella tbd = f i r s t ;
f i r s t = f i r s t >s u ;
tbd ;

delete

}
numVoti = 0 ;

unsigned int

V o t a z i o n i : : G e t V o t i P a r t i t o ( Codi e i d )
PCella p = C e r a P a r t i t o ( i d ) ;

if ( p )
return
else
return

onst

p>elem . v o t i ;
0;

unsigned int V o t a z i o n i : : GetNumeroVoti ( ) onst


return numVoti ;

void

Votazioni : : GetSituazione ()
PCella p = f i r s t ;

while

onst

(p) {
out << " P a r t i t o " << p>elem . i d << " : v o t i " << " " << p>elem . v o t i ;
out << " ( " << (
) p>elem . v o t i /numVoti 100 << "%)" << e n d l ;

void
void
void
void
void
void

p = p>s u ;

AggiungiVoto ( V o t a z i o n i& v ) ;
Svuota ( V o t a z i o n i& v ) ;
G e t V o t i P a r t i t o ( V o t a z i o n i& v ) ;
GetNumeroVoti ( V o t a z i o n i& v ) ;
G e t S i t u a z i o n e ( V o t a z i o n i& v ) ;

stampa_menu( ) {
out << " 1 : Aggiungi voto . \ n" ;
out << " 2 : Svuota . \ n" ;
out << " 3 : Voti p a r t i t o . \ n" ;
out << " 4 : Numero v o t i . \ n" ;
out << " 5 : S i t u a z i o n e . \ n" ;
out << " 6 : E s i . \ n" ;

int

float

main ( )

Votazioni v ;

SX. Soluzioni degli altri eser izi

160

int s e l t a ;
do {

stampa_menu ( ) ;
i n >> s e l t a ;
( s elta ) {
1:
AggiungiVoto ( v ) ;
;
2:
Svuota ( v ) ;
;
3:
GetVotiPartito ( v ) ;
;
4:
GetNumeroVoti ( v ) ;
;
5:
GetSituazione (v ) ;
;
6:
;
:
out << " S e l t a non v a l i d a . \ n" ;
;
}
}
( s e l t a != 6 ) ;

swit h
ase
break
ase
break
ase
break
ase
break
ase
break
ase
break
default
break
while
return 0 ;

void

AggiungiVoto ( V o t a z i o n i& v ) {
Codi e i d ;
out << " I n d i a r e i l p a r t i t o : " ;
i n >> i d ;
out << " Voto Aggiunto . Ora i l p a r t i t o " << i d << " ha v o t i " <<
v . AggiungiVoto ( i d ) << " . \ n" ;

void
}

Svuota ( V o t a z i o n i& v ) {
v . Svuota ( ) ;
out << " S t r u t t u r a s v u o t a t a . " << e n d l ;

void

G e t V o t i P a r t i t o ( V o t a z i o n i& v ) {
Codi e i d ;
out << " I n d i a r e i l p a r t i t o : " ;
i n >> i d ;
out << " I l p a r t i t o " << i d << " ha o t t e n u t o v o t i " <<
v . G e t V o t i P a r t i t o ( i d ) << " . \ n" ;

void
}

GetNumeroVoti ( V o t a z i o n i& v ) {
out << " I v o t i o m p l e s s i v i sono : " << v . GetNumeroVoti ( ) << e n d l ;

void
}

G e t S i t u a z i o n e ( V o t a z i o n i& v ) {
v . GetSituazione ( ) ;

Appendi e A
GNU Free Do umentation Li ense
Version 1.2, November 2002
2000,2001,2002 Free Software Foundation, In .
Copyright
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to opy and distribute verbatim opies of this li ense do ument,
but hanging it is not allowed.
Preamble
The purpose of this Li ense is to make a manual, textbook, or other fun tional and
useful do ument free in the sense of freedom: to assure everyone the ee tive freedom to
opy and redistribute it, with or without modifying it, either ommer ially or non ommer ially. Se ondarily, this Li ense preserves for the author and publisher a way to get redit
for their work, while not being onsidered responsible for modi ations made by others.
This Li ense is a kind of opyleft, whi h means that derivative works of the do ument
must themselves be free in the same sense. It omplements the GNU General Publi
Li ense, whi h is a opyleft li ense designed for free software.
We have designed this Li ense in order to use it for manuals for free software, be ause
free software needs free do umentation: a free program should ome with manuals providing the same freedoms that the software does. But this Li ense is not limited to software
manuals; it an be used for any textual work, regardless of subje t matter or whether it
is published as a printed book. We re ommend this Li ense prin ipally for works whose
purpose is instru tion or referen e.

A.1 Appli ability and Denitions


This Li ense applies to any manual or other work, in any medium, that ontains a noti e
pla ed by the opyright holder saying it an be distributed under the terms of this Li ense.
Su h a noti e grants a world-wide, royalty-free li ense, unlimited in duration, to use that
work under the onditions stated herein. The Do ument, below, refers to any su h
manual or work. Any member of the publi is a li ensee, and is addressed as you. You

161

A. GNU Free Do umentation Li ense

162

a ept the li ense if you opy, modify or distribute the work in a way requiring permission
under opyright law.
A Modied Version of the Do ument means any work ontaining the Do ument
or a portion of it, either opied verbatim, or with modi ations and/or translated into
another language.
A Se ondary Se tion is a named appendix or a front-matter se tion of the Do ument
that deals ex lusively with the relationship of the publishers or authors of the Do ument
to the Do ument's overall subje t (or to related matters) and ontains nothing that ould
fall dire tly within that overall subje t. (Thus, if the Do ument is in part a textbook of
mathemati s, a Se ondary Se tion may not explain any mathemati s.) The relationship
ould be a matter of histori al onne tion with the subje t or with related matters, or of
legal, ommer ial, philosophi al, ethi al or politi al position regarding them.
The Invariant Se tions are ertain Se ondary Se tions whose titles are designated,
as being those of Invariant Se tions, in the noti e that says that the Do ument is released
under this Li ense. If a se tion does not t the above denition of Se ondary then it is not
allowed to be designated as Invariant. The Do ument may ontain zero Invariant Se tions.
If the Do ument does not identify any Invariant Se tions then there are none.
The Cover Texts are ertain short passages of text that are listed, as Front-Cover
Texts or Ba k-Cover Texts, in the noti e that says that the Do ument is released under
this Li ense. A Front-Cover Text may be at most 5 words, and a Ba k-Cover Text may
be at most 25 words.
A Transparent opy of the Do ument means a ma hine-readable opy, represented
in a format whose spe i ation is available to the general publi , that is suitable for revising the do ument straightforwardly with generi text editors or (for images omposed
of pixels) generi paint programs or (for drawings) some widely available drawing editor,
and that is suitable for input to text formatters or for automati translation to a variety
of formats suitable for input to text formatters. A opy made in an otherwise Transparent le format whose markup, or absen e of markup, has been arranged to thwart or
dis ourage subsequent modi ation by readers is not Transparent. An image format is not
Transparent if used for any substantial amount of text. A opy that is not Transparent is
alled Opaque.
Examples of suitable formats for Transparent opies in lude plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publi ly available
DTD, and standard- onforming simple HTML, PostS ript or PDF designed for human
modi ation. Examples of transparent image formats in lude PNG, XCF and JPG. Opaque formats in lude proprietary formats that an be read and edited only by proprietary
word pro essors, SGML or XML for whi h the DTD and/or pro essing tools are not generally available, and the ma hine-generated HTML, PostS ript or PDF produ ed by some
word pro essors for output purposes only.
The Title Page means, for a printed book, the title page itself, plus su h following
pages as are needed to hold, legibly, the material this Li ense requires to appear in the title
page. For works in formats whi h do not have any title page as su h, Title Page means
the text near the most prominent appearan e of the work's title, pre eding the beginning
of the body of the text.
A se tion Entitled XYZ means a named subunit of the Do ument whose title either
is pre isely XYZ or ontains XYZ in parentheses following text that translates XYZ in
another language. (Here XYZ stands for a spe i se tion name mentioned below, su h as
A knowledgements, Dedi ations, Endorsements, or History.) To Preserve the

A. GNU Free Do umentation Li ense

163

Title of su h a se tion when you modify the Do ument means that it remains a se tion
Entitled XYZ a ording to this denition.
The Do ument may in lude Warranty Dis laimers next to the noti e whi h states that
this Li ense applies to the Do ument. These Warranty Dis laimers are onsidered to be
in luded by referen e in this Li ense, but only as regards dis laiming warranties: any other
impli ation that these Warranty Dis laimers may have is void and has no ee t on the
meaning of this Li ense.

A.2 Verbatim Copying


You may opy and distribute the Do ument in any medium, either ommer ially or non ommer ially, provided that this Li ense, the opyright noti es, and the li ense noti e
saying this Li ense applies to the Do ument are reprodu ed in all opies, and that you
add no other onditions whatsoever to those of this Li ense. You may not use te hni al
measures to obstru t or ontrol the reading or further opying of the opies you make
or distribute. However, you may a ept ompensation in ex hange for opies. If you distribute a large enough number of opies you must also follow the onditions in se tion
3.
You may also lend opies, under the same onditions stated above, and you may
publi ly display opies.

A.3 Copying in Quantity


If you publish printed opies (or opies in media that ommonly have printed overs) of the
Do ument, numbering more than 100, and the Do ument's li ense noti e requires Cover
Texts, you must en lose the opies in overs that arry, learly and legibly, all these Cover
Texts: Front-Cover Texts on the front over, and Ba k-Cover Texts on the ba k over.
Both overs must also learly and legibly identify you as the publisher of these opies.
The front over must present the full title with all words of the title equally prominent
and visible. You may add other material on the overs in addition. Copying with hanges
limited to the overs, as long as they preserve the title of the Do ument and satisfy these
onditions, an be treated as verbatim opying in other respe ts.
If the required texts for either over are too voluminous to t legibly, you should put
the rst ones listed (as many as t reasonably) on the a tual over, and ontinue the rest
onto adja ent pages.
If you publish or distribute Opaque opies of the Do ument numbering more than 100,
you must either in lude a ma hine-readable Transparent opy along with ea h Opaque
opy, or state in or with ea h Opaque opy a omputer-network lo ation from whi h
the general network-using publi has a ess to download using publi -standard network
proto ols a omplete Transparent opy of the Do ument, free of added material. If you use
the latter option, you must take reasonably prudent steps, when you begin distribution of
Opaque opies in quantity, to ensure that this Transparent opy will remain thus a essible
at the stated lo ation until at least one year after the last time you distribute an Opaque
opy (dire tly or through your agents or retailers) of that edition to the publi .
It is requested, but not required, that you onta t the authors of the Do ument well
before redistributing any large number of opies, to give them a han e to provide you
with an updated version of the Do ument.

A. GNU Free Do umentation Li ense

164

A.4 Modi ations


You may opy and distribute a Modied Version of the Do ument under the onditions
of se tions 2 and 3 above, provided that you release the Modied Version under pre isely
this Li ense, with the Modied Version lling the role of the Do ument, thus li ensing
distribution and modi ation of the Modied Version to whoever possesses a opy of it.
In addition, you must do these things in the Modied Version:
A. Use in the Title Page (and on the overs, if any) a title distin t from that of the
Do ument, and from those of previous versions (whi h should, if there were any,
be listed in the History se tion of the Do ument). You may use the same title as a
previous version if the original publisher of that version gives permission.
B. List on the Title Page, as authors, one or more persons or entities responsible for
authorship of the modi ations in the Modied Version, together with at least ve
of the prin ipal authors of the Do ument (all of its prin ipal authors, if it has fewer
than ve), unless they release you from this requirement.
C. State on the Title page the name of the publisher of the Modied Version, as the
publisher.
D. Preserve all the opyright noti es of the Do ument.
E. Add an appropriate opyright noti e for your modi ations adja ent to the other
opyright noti es.
F. In lude, immediately after the opyright noti es, a li ense noti e giving the publi
permission to use the Modied Version under the terms of this Li ense, in the form
shown in the Addendum below.
G. Preserve in that li ense noti e the full lists of Invariant Se tions and required Cover
Texts given in the Do ument's li ense noti e.
H. In lude an unaltered opy of this Li ense.
I. Preserve the se tion Entitled History, Preserve its Title, and add to it an item
stating at least the title, year, new authors, and publisher of the Modied Version
as given on the Title Page. If there is no se tion Entitled History in the Do ument,
reate one stating the title, year, authors, and publisher of the Do ument as given
on its Title Page, then add an item des ribing the Modied Version as stated in
the previous senten e.
J. Preserve the network lo ation, if any, given in the Do ument for publi a ess to
a Transparent opy of the Do ument, and likewise the network lo ations given in
the Do ument for previous versions it was based on. These may be pla ed in the
History se tion. You may omit a network lo ation for a work that was published
at least four years before the Do ument itself, or if the original publisher of the
version it refers to gives permission.
K. For any se tion Entitled A knowledgements or Dedi ations, Preserve the Title of
the se tion, and preserve in the se tion all the substan e and tone of ea h of the
ontributor a knowledgements and/or dedi ations given therein.
L. Preserve all the Invariant Se tions of the Do ument, unaltered in their text and in
their titles. Se tion numbers or the equivalent are not onsidered part of the se tion
titles.

A. GNU Free Do umentation Li ense

165

M. Delete any se tion Entitled Endorsements. Su h a se tion may not be in luded in


the Modied Version.
N. Do not retitle any existing se tion to be Entitled Endorsements or to oni t in
title with any Invariant Se tion.
O. Preserve any Warranty Dis laimers.
If the Modied Version in ludes new front-matter se tions or appendi es that qualify
as Se ondary Se tions and ontain no material opied from the Do ument, you may at
your option designate some or all of these se tions as invariant. To do this, add their titles
to the list of Invariant Se tions in the Modied Version's li ense noti e. These titles must
be distin t from any other se tion titles.
You may add a se tion Entitled Endorsements, provided it ontains nothing but endorsements of your Modied Version by various partiesfor example, statements of peer
review or that the text has been approved by an organization as the authoritative denition
of a standard.
You may add a passage of up to ve words as a Front-Cover Text, and a passage of
up to 25 words as a Ba k-Cover Text, to the end of the list of Cover Texts in the Modied
Version. Only one passage of Front-Cover Text and one of Ba k-Cover Text may be added
by (or through arrangements made by) any one entity. If the Do ument already in ludes
a over text for the same over, previously added by you or by arrangement made by the
same entity you are a ting on behalf of, you may not add another; but you may repla e
the old one, on expli it permission from the previous publisher that added the old one.
The author(s) and publisher(s) of the Do ument do not by this Li ense give permission
to use their names for publi ity for or to assert or imply endorsement of any Modied
Version.

A.5 Combining Do uments


You may ombine the Do ument with other do uments released under this Li ense, under
the terms dened in se tion 4 above for modied versions, provided that you in lude in
the ombination all of the Invariant Se tions of all of the original do uments, unmodied,
and list them all as Invariant Se tions of your ombined work in its li ense noti e, and
that you preserve all their Warranty Dis laimers.
The ombined work need only ontain one opy of this Li ense, and multiple identi al
Invariant Se tions may be repla ed with a single opy. If there are multiple Invariant
Se tions with the same name but dierent ontents, make the title of ea h su h se tion
unique by adding at the end of it, in parentheses, the name of the original author or
publisher of that se tion if known, or else a unique number. Make the same adjustment
to the se tion titles in the list of Invariant Se tions in the li ense noti e of the ombined
work.
In the ombination, you must ombine any se tions Entitled History in the various
original do uments, forming one se tion Entitled History; likewise ombine any se tions
Entitled A knowledgements, and any se tions Entitled Dedi ations. You must delete all
se tions Entitled Endorsements.

A. GNU Free Do umentation Li ense

166

A.6 Colle tion of Do uments


You may make a olle tion onsisting of the Do ument and other do uments released under
this Li ense, and repla e the individual opies of this Li ense in the various do uments
with a single opy that is in luded in the olle tion, provided that you follow the rules of
this Li ense for verbatim opying of ea h of the do uments in all other respe ts.
You may extra t a single do ument from su h a olle tion, and distribute it individually under this Li ense, provided you insert a opy of this Li ense into the extra ted
do ument, and follow this Li ense in all other respe ts regarding verbatim opying of that
do ument.

A.7 Aggregation with Independent Works


A ompilation of the Do ument or its derivatives with other separate and independent
do uments or works, in or on a volume of a storage or distribution medium, is alled an
aggregate if the opyright resulting from the ompilation is not used to limit the legal
rights of the ompilation's users beyond what the individual works permit. When the
Do ument is in luded in an aggregate, this Li ense does not apply to the other works in
the aggregate whi h are not themselves derivative works of the Do ument.
If the Cover Text requirement of se tion 3 is appli able to these opies of the Do ument,
then if the Do ument is less than one half of the entire aggregate, the Do ument's Cover
Texts may be pla ed on overs that bra ket the Do ument within the aggregate, or the
ele troni equivalent of overs if the Do ument is in ele troni form. Otherwise they must
appear on printed overs that bra ket the whole aggregate.

A.8 Translation
Translation is onsidered a kind of modi ation, so you may distribute translations of the
Do ument under the terms of se tion 4. Repla ing Invariant Se tions with translations
requires spe ial permission from their opyright holders, but you may in lude translations
of some or all Invariant Se tions in addition to the original versions of these Invariant
Se tions. You may in lude a translation of this Li ense, and all the li ense noti es in
the Do ument, and any Warranty Dis laimers, provided that you also in lude the original
English version of this Li ense and the original versions of those noti es and dis laimers.
In ase of a disagreement between the translation and the original version of this Li ense
or a noti e or dis laimer, the original version will prevail.
If a se tion in the Do ument is Entitled A knowledgements, Dedi ations, or History,
the requirement (se tion 4) to Preserve its Title (se tion 1) will typi ally require hanging
the a tual title.

A.9 Termination
You may not opy, modify, subli ense, or distribute the Do ument ex ept as expressly provided for under this Li ense. Any other attempt to opy, modify, subli ense or distribute
the Do ument is void, and will automati ally terminate your rights under this Li ense.

A. GNU Free Do umentation Li ense

167

However, parties who have re eived opies, or rights, from you under this Li ense will not
have their li enses terminated so long as su h parties remain in full omplian e.

A.10 Future revisions of this li ense


The Free Software Foundation may publish new, revised versions of the GNU Free Do umentation Li ense from time to time. Su h new versions will be similar in spirit to
the present version, but may dier in detail to address new problems or on erns. See
http://www.gnu.org/ opyleft/.
Ea h version of the Li ense is given a distinguishing version number. If the Do ument
spe ies that a parti ular numbered version of this Li ense or any later version applies
to it, you have the option of following the terms and onditions either of that spe ied
version or of any later version that has been published (not as a draft) by the Free Software
Foundation. If the Do ument does not spe ify a version number of this Li ense, you may
hoose any version ever published (not as a draft) by the Free Software Foundation.

How to use this Li ense for your do uments


To use this Li ense in a do ument you have written, in lude a opy of the Li ense in the
do ument and put the following opyright and li ense noti es just after the title page:
YEAR YOUR NAME. Permission is granted to opy, distribute
Copyright
and/or modify this do ument under the terms of the GNU Free Do umentation Li ense, Version 1.2 or any later version published by the Free Software
Foundation; with no Invariant Se tions, no Front-Cover Texts, and no Ba kCover Texts. A opy of the li ense is in luded in the se tion entitled GNU
Free Do umentation Li ense.
If you have Invariant Se tions, Front-Cover Texts and Ba k-Cover Texts, repla e the
with...Texts. line with this:
with the Invariant Se tions being LIST THEIR TITLES, with the FrontCover Texts being LIST, and with the Ba k-Cover Texts being LIST.
If you have Invariant Se tions without Cover Texts, or some other ombination of the
three, merge those two alternatives to suit the situation.
If your do ument ontains nontrivial examples of program ode, we re ommend releasing these examples in parallel under your hoi e of free software li ense, su h as the GNU
General Publi Li ense, to permit their use in free software.

Bibliograa
[1 Bjarne Stroustrup.
edition, 2000.

The C++ Programming Language. Addison-Wesley, spe ial

[2 Bru e E kel. Thinking in C++, Volume 1: Introdu tion to Standard C++. Prenti e
Hall, 2nd edition, 2000. Liberamente s ari abile da http://www.bru ee kel. om.
Disponibile an he in versione italiana edita da Apogeo.
[3 Carlo Savy.

Da C++ ad UML: guida alla progettazione. M Graw Hill, 2000.

[4 SGI. C++ Standard Template Library (STL). http://www.sgi. om/te h/stl.


[5 S ott Meyers. Ee tive C++: 55 Spe i
Designs. Addison-Wesley, 3rd edition, 2005.

Ways to Improve Your Programs and

[6 GCC. GNU/GCC, the GNU ompiler olle tion. http://g .gnu.org.


[7 ISO/IEC.
International Standard for C++. International Organization for
Standardization (ISO), 2st edition, 2003. http://www.ansi.org.
[8 Bloodshed Software. Dev-C++. http://www.bloodshed.net/dev pp.html.
[9 E. Gamma, R. Helm, R. Johnson, and J. Vlissides. Design
Reusable Obje t-Oriented Software. Addison-Wesley, 1995.
[10 S ott Meyers. More Ee tive C++:
Designs. Addison-Wesley, 1995.

Patterns: Elements of

35 New Ways to Improve Your Programs and

[11 Andrei Alexandres u. Modern C++ Design:


Patterns Applied. Addison-Wesley, 2001.

168

Generi Programming and Design

Potrebbero piacerti anche