Каррано_Абстракция данных и решение задач на C++

849

Transcript of Каррано_Абстракция данных и решение задач на C++

C++

DATA ABSTRACTION AND PROBLEM SOLVING WITH C++WALLS AND MIRRORSThird Edition

Frank M. Carrano University of Rhode Island Janet J. Prichard Bryant College

A TTADDISON-WESLEY PUBLISHING COMPANY Boston San Francisco New York London Toronto Sydney Tokyo Singapore Madrid Mexico City Munich Paris Cape Toxvn Hong Kong Montreal

C++

. .

- 2003

32.973.26-018.2.75 26 681.3.07

"" . .. . .-. >4. "" : [email protected], http://www.williamspublishing.com

.., .. 26 C+-I-. , 3- . : . . .: "", 2003. 848 : . . . . ISBN 5-8459-0389-0 (.) , , , C+-I-. , , - . - , , , , C++. , C++. 32.973.26-018.2.75 . , , , Addison-Wesley Publishing Company, Inc. Authorized translation from the English language edition published by Pearson Education, Inc, Copyright 2002 All rights reserved. No part of this book may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording or by any information storage retrieval system, without permission from the Publisher. Russian language edition published by Williams Publishing House according to the Agreement with R&I Enter prises International, Copyright 2003

ISBN 5-8459-0389-0 ( ) ISBN 0-2017-4119-9 (.)

"", 2003 Pearson Education, Inc., 2002

I. 1. 2. : 3. : 4. 5. II. 6. 7. 8. -+ 9. 10. 11. 12. 13. 14. . + . ASCII- . C++ . . . C++

13 23 24 69 123 169 236 267 268 319 358 408 455 535 579 645 681 719 788 790 795 800 803 806 825 844

I. 1. - " " - UML -

13 13 14 14 14 15 16 16 16 17 17 18 19 19 19 23 24 25 25 26 34 36 36 38 40 41 42 44 45 45 47 49 50 55 61 63 64 64 65 67

2. : , : , : ( ) ( ) - 3 . : C+-f C++ 4 . , ,

69 70 73 79 90 90 92 94 96 97 98 102 105 105 109 114 115 115 116 122 123 124 129 130 135 136 140 142 143 152 154 159 160 162 163 164 165 167 169 170 170 176 179 181 181 183 185 190 197 199 202

7

, : C++ list STL 5. II. 6. stack : :

203 208 209 209 211 211 214 219 220 221 222 224 226 227 229 232 236 237 237 241 242 243 246 254 255 256 257 258 258 258 261 267 268 269 269 274 275 277 278 279 282 285 288 289 290 291 292 295 297 304 307

8

7. queue STL , : 8. C + + , "", "" "" 9. 0-

308 309 309 310 313 319 320 322 322 323 324 325 330 335 337 340 341 342 351 351 351 352 354 358 359 365 366 368 373 377 380 382 386 392 395 397 401 402 402 403 406 408 409 410 411 413 417 419 420 424 426

9

10. ,

428 433 444 446 447 447 448 449 452 455 457 463 467 470 474 488 492 506 514 518 519 522 524 525 525 527 532

11. : 1 2 . 2-3 2-3-4 - AVL-

535536 541 548 552 555 558 567 569 573 574 574 575 577 579 580 581 599 607 611 615 619 621

10

: 1 3 . 14. -

629 632 634 635 640 640 641 641 644 645 646 649 650 653 654 656 657 657 661 665 668 672 674 676 676 676 677 680 681 682 685 692 694 698 701 711 713 714 715 715 716 718

. 4-+ typedef

719720 721 721 721 722 723 724 724 725

11

if switch while for do +4 J a v a . ASCII- C + + . ++ . . . + +

725 730 730 731 732 734 737 737 737 738 740 740 741 743 743 743 745 747 748 749 750 753 755 755 755 756 760 762 763 773 774 775 775 780 782 783 785 786 788 790 795 798 799 800 803 806 825 844

12

" C++: ". - , C++ . (Paul Helman) (Robert Veroff) Intermediate Problem Solving and Data Structures: Walls and Mirrors. ; , , , , . . . , . , , , . , , . , - .

. , , . , . , , . . , , , , . . , ( . . .) , , . C++ , , , . , " ". , C++. , , , . , , : is switch, for, while do, , , , . C++ 1, 3 8, . , -

, , 2 5. , , . , .

. C++. , .

, +, C++, , . , . , - , , , . () , , C++. - . , - , . , (Universal Modeling Language UML).

, . . . . , . , , . , . . , , 8, ( 6). ( 9) 5. , . , , . , ( 14) , . , ( 9).

14

*|551 1 , ^ , ,

1

3 2 4 5

6 ?";"'>,

7

8 C++

9 ,

10

13

11 ,

12 14

:^^^'611>, .

"" . , . , , .

15

. . . -+ . , . , , , , , .

, , , , . , , , , . . . , , , ; , . . . , . , , , . . , , - , , . .

, , . , , , . , , . . , , . , ; , - ; , .

. , C+-f. , 16

, . , . , . , -+. . . UML. , . 1 - UML. , , . , Java, , . 3 . , , -+. , . 4 , C++ (STL). , . 8 . 4 list STL. SDL. . 6 stack STL. 7 queue STL. 8 . , . C++, . , C++. . list, stack queue STL.

, .

, . . , . 17

. ( . . .) . . . . . , , UML. C++ . . , C++. .

. , 1-11 , . 1 2 . 11-14 . I. . 1 . UML. . . . . 5 . , , . 3 , (). C++, . , . 4 , . , , C++ (STL), . , I, . II. . . , : , , , , , . . . . 18

8 , , . . 9 0-. , . II , , (2-3, 2-3-4, - AVL-) . . . , -. 2-3 , .

Internet. . , , , www.aw.com/cssupport. . , . , , www.aw.com/cssupport.

. , . [email protected]

[email protected]

Computer Science Editorial Office Addison-Wesley 75 Arlington Street Boston, MA 02116

, , . . (Vicki . Allan) (Utah State University) (Don Bailey) (Carleton University) (Sebastian Elbaum) , . (University of Nebraska, Lincoln) 19

(Matthew Evett) (Eastern Michigan University) (Susan Gauch) (University of Kansas) (Martin Granier) (Western Washington University) (Judy Hankins) (Middle Tennessee State University) - (Sr. Joan Harnett) (Manhattan College) (Tom Irby) (University of North Texas) . (Edwin J. Kay) Jlexaii (Lehigh University) (David Naffin) (Fullerton College) (Paul Nagin) (Hofstra University) (Bina Ramamurthy) SUNY . (SUNY at Buffalo) (Dwight Tunistra) (Karen VanHouten) (University of Idaho) (Kathie Yerion) (Gonzaga University) , . Addison-Wesley, (Susan Hartman) (Katherine Harutunian), . , (Daniel Rausch) Argosy Publishing. . (Rebecca Pepper), . (Pat Mantani), (Michael Hitsch), (Gina Hagen), (Jarrod Gibbons), (Michelle Renda) (Joe Vetere), . . : (Doug McCreadie), (Michael Hayden), (Sarah Hayden), (Andrew Hayden), (Albert Prichard), (Ted Emmott), (Maybeth Conway), (Lorraine Berube), (Marge White), (James Kowalski), (Gerard Baudet), (Joan Peckham), (Ed Lamagna), - (Victor Fay-Wolfe), (Bala Ravikumar), (Lisa DiPippo), - (Jean-Yves Herve), (Hal Records), (Wally Wood), (Elaine Lavallee), (Ken Sousa), (Sally Lawrence), (Lianne Dunn), (Gail Armstrong), ( Manning), (Jim Labonte), (Jim Abreu) (Bill Harding). , . . . (Karl Abrahamson), (Stephen Alberg), (Ronald Alferez), (Vicki Allan), (Jihad 20

Almahayni), (James Ames), . (Claude W. Anderson), (Andrew Azzinaro), (Tony Baiching), (Don Bailey), . (N. Dwight Barnette), (Jack Beidler), . (Wolfgang W. Bein), (Sto Bell), (David Berard), (John Black), (Richard Botting), (Wolfin Brumley), (Philip Carrigan), (Stephen damage), (Michael Clancy), (David Clayton), (Michael Cleron), (Chris Constantino), (Shaun Cooper), (Charles Denault), . (Vincent J. DiPippo), (Suzanne Dorney), (Colleen Dunn), (Carl Eckberg), (Karla Steinbrugge Fant), (Jean Foltz), (Susan Gauch), (Marguerite Hafen), (Randy Hale), (George Hamer), (Judy Hankins), (Lisa Hellerstein), ( Lou Hines), (Jack Hodges), (Stephanie Horoschak), (Lily ), (John Hubbard), (Kris Jensen), (Thomas Judson), (Laura Kenney), (Roger King), (Ladislav Kohout), (Jim LaBonte), (Jean Lake), (Janusz Laski), (Cathie LeBlanc), (Urban LeJeune), . (John . Linebarger), (Ken Lord), (Paul Luker), (Manisha Mande), - (PierreArnoul de Marneffe), (John Marsaglia), (Jane Wallace Mayo), (Mark McCormick), (Dan McCracken), (Vivian McDougal), (Shirley McGuire), (Sue Medeiros), (Jim Miller), (Guy Mills), (Rameen Mohammadi), (Cleve Moler), (Narayan Murthy), (Paul Nagin), (Rayno Niemi), ' (John O'Donnell), (Andrew Oldroyd), (Larry Olsen), . (Raymond L. Paden), (Roy Pargas), . (Brenda . Parker), . (Thaddeus F. Pawlicki), (Keith Pierce), (Lucasz Pruski), . (George . Purdy), (David Radford), (Steve Ratering), (Stuart Regis), . . (J. D. Robertson), . (Robert . Rossi), (John Rowe), . (Michael . Rupp), (Sharon Salveter), (Charles Saxon), (Chandra Sekharan), (Linda Shapiro), (Yujian Sheng), ( Shields), (Ronnie Smith), (Carl Spicola), (Richard Snodgrass), (Neil Snyder), (Chris Spannabel), (Paul Spirakis), (Clinton Staley), (Matt Stallman), (Mark Stehlick), . (Benjamin . Schomp), (Harriet Taylor), (David Teague), (David Tetreault), (John Turner), (Susan Wallace), . (James . Warren), (Jerry Weltman), (Nancy Wiegand), (Howard Williams), (Brad Wilson), (James Wirth), (Salih Yurttas) (Alan Zaring). ! F.M.C J.J.P.

21

I

1

... - " '' - , UML , -

. , ; . , , . . , . . , , .

, ? , , . , , , , , . , , , , , , . . , , , , , , ? , . , , . , . . , (software engineering) . , , . 1 , . .

(solving problem) , . , , . ? (solution) : . (algorithm) . . , , . 1. 25

, , , . . , , . . , . .

, (software's life cycle). , , . . 1.1 . , , . , . , , . , , , . , , .

. 1.1. , (Raymond L. Paden) .

26

I.

. , . 1. . , . , , , . , . , . ? , ? ? ? ? ? ? ? ? ? - i (prototype programms), - I . , . , . , . , , , , , . 2. . , . , , , . , , . (modules), . , . , , (loosely coupled) . , (interfaces), . . , . , (highly cohesive). , (modularity) , . , , (data flow) , . , , . 1. 27

? ? ? , , . , , . , > 0. , . | - (contract) | . , . , . , , . , . , . - , , . , , , . , . . - "", . (precondition) (postcondition) , , , , . , , , .^ s o r t (, ) 1 / / . // : , // ; > 0. // : . - . , : ? ? , , , 100. , , sort 500 . , - .

.

28

I.

sort (, ) j / / ' " "" " / / . // : , // ; 1 last]. * ( , .) [first. .last] : Si, , ; ; S2, , . , , Si, , S2. . 2.18.Si S2

first

f pivotlndex

last

. 2.18. 2. : 103

[first. .ivotIndex-1] , , [first. .pivotlndex+l] . , Si S2 , [first. .last], , . 1. Si / , k [first.. last], k-u Si. Si [first. .pivot Index-1], , k < pivotIndex-first+1, 2. Si k-1 , k- . . , k = pivotIndex-first+1, 3. Si , k~l , - [first.. last] S2. Si pivotlndex-first , k- [first.. last] (- (pivotlndex-first+l)'M S2. , k>pivotIndex-first+1, . kSmalKk, , [first..last] first, last) = - - anArray[first..last]

[first.. last] Si S2 ; .

kSmall(k, , first last)

kSmall(k, , first, pivotlndex - 1), < pivotlndex - first + 1, p, k = pivotlndex - first + 1 kSmall(k - {pivotlndex - first +1), anArray, pivotlndex + 1, L), / > pivotlndex - first + 1.

; , Si S2, , , 1. , : . . kSmall (in K;indeger, in :ArrayType, in first: integer, in last: integer) : ItemType // - [first..last]. [first..last] [first..last] If ( < pivotlndex return kSmall(, - first + 1) , first, pivotIndex-1) I.

104

else

if ( == pivotlndex return p return

~ first

-h 1)

else

kSmall(k-(pivotlndex-first+1), pivotIndex+1, last)

anArray,

4-+. , . . , . 9 . kSmall .

-. . , .

- . , , . ( ) : (), () (). . . - . , . 2.19, . , . , , , , , . , . . , . " , . ." . , . " , , , ." , . " (.. =1), . . (.. >1), . 1. -1 , , (. 2.19, ). 2. -1 , . 2. : 105

=1 ( ), (. 2.19, ). 3. , .. , , , (. 2.19, )." . : " , ?" . , , . ( ). ; count source destination spare, towers (count, source, destination, spare). , , source , count ( count , ). , destination spare . , , . , . , , i . - 1 : , . towers (, . , ),

A A

B

C

i I1B C

11)

. 2.19. : ) ; ) -1 ; ) ; ) -1 106 I.

, , i . 1. , A, towers(~1, , , ). , ( ) ( - 1 ) , . , . 2. , , , towers(1, , , ) . , . , , . , , . , . 3. , , , towers(-1, , , ). , -1 B, . , , . : . towers (count, source, destination, spare) . solveTowers(count, if else{

source,

destination,

spare) source

( count 1) destination

solveTowers(count-1, source, spare, destination) solveTowers(1, source, destination, spare) solveTowers(count-1, spare, destination, source) } // if , . 1. . 2. : , , , 1. 2. : 107

3. , . 4. , , . , . . 2.20 ; , . 1solveTowers(3,,,)

solveTowers(2,,,) solveTowers(1,,,) solveTowers(2,,,)

1solveTowers(1,,,) solveTowers(1,,,)

4solveTowers(1,,,) solveTowers(1,,,)

^ 5 1solveTowers(1,,,)

10

solveTowers(1,,,)

. 2.20. , solveTowers(3, , , ) C++. , , . , , , char, ' ' , ' ' ' . solveTowers (3, ' ' , ' ' , '') .

C++ . void solveTowers(int count, char source, char d e s t i n a t i o n , c h a r spare){

if {

(count == 1)cout 0. 15.1. powerl > 0. 15.2. poiver2 , : " = * " \ > 0. 15.3. power3 J\JIR '\ : " = (:"^ ) , > ,

" = * {^^^')^, > . 15.4. powerl, power2 power3 3^^ 3^^? 15.5. power2 powers 3 3 ? 16. rabbit , . " :" " :" , . , r a b b i t(4) . r a b b i t : = 4 r a b b i t : = 3 r a b b i t : = 2 2 r a b b i t : = 2 value = 1 r a b b i t : = 1 r a b b i t : = 1 value = 1 r a b b i t : = 3 val ue = 2 r a b b i t : = 2 r a b b i t : = 2 value = 1 r a b b i t : = 4 v a l u e = 3 . 2.11. 17. : /(1)-=1; /(2)=1; /(3)=1; /(4)=3; /(5)=5; f{n)=f{n-l)+'^'^f{n-b) > 5. 17.1. f{n) : 6, 7, 12, 15. 17.2. /(15) ( 4-+), /(6), /(7), /(8), /(15), . . (, rabbit .)

120

I.

, . , +- , f{n) . 18. writeBackward, binarySearch kSmall, fact,

19. , , HerativeRabbit, " ", .

20. (gcd g r e a t e s t common divisor) b. , . . b , > b , gcd(a, b)=gcd(b, mod b). gcd(a, b) gcd(^, mod b) . gcd(a, b) . , b , b=gcd(a, ), ( mod b) = 0. : gcd{a,b) \, ( mod b) = , [gcd(bj mod b), ( mod b) 0. C + + . i n t g c d ( i n t , i n t b)

{(a % b == 0) / / r e t u r n a; else return gcd(b, a % b ) ; } / / g c d 20.1. . 20.2. , >7 20.3. ? ( ?) ? 21. () , 1 - 1 , ( , 4 = 1 + 1 + 1 + 1 = 1 + 1 + 2 = . . . = 2 + 2 ) . () . 21.1. . , 1, 2, 1 1, 1, 2 . 21.2. . 22. : modulo ( ) mod. C++ % .

if

2. :

121

n + \, - 0, Acker(m, n) - \ Acker{m - 1,1), n = 0, Acker(m - 1, Acker{m, n - 1)), m ^ ^ 0. , (Ackerman's function), , . Acker(l, 2)? C++ Acker(l, 2) -. (: .)

C++ , " k- ". ? C++ kSmall, " k- ", .

122

I.

3

:

... C++ C++

. , 1, . **" . , (). . . , , . 4-+.

- i ^, , 1 . , . , , . , . , . ^ ^^ - l. , ,,.,, -.-.---....,.,.,. .. . , , , . , , , . , , , , , ; . , , , . (functional abstraction). , , . (information hiding) , . , . . " " . , Q , , , - , Q. . 3.1, Q . . Q , , , . , , , . , S, ; . , S , , . , , 124 I.

- 4

1^^^ ^ ^.

:1'^,

^4^'1

^

=

^'< next = c u r ; prev->next = newPbr; 100

prev

newPtr . 4.12. , . neviPtry prev ? ?

4.

185

, , , . prev . , ; . , newPtr, newPtr = new Node;

, ; , , . : , , . -, , . 4.13. head, , . . newPtr->next = head; head = newPtr;

head

f-

100

z

newPtr prev

. 4.13. , head NULL, , next, , NULL, , , . . 4.14 cur . NULL, , newPtr->next = cur; prev->next = newPtr;

, prev. , ? NULL, , NULL, NULL, prev , . , . 186 I.

head

f-

3

100

I

z

newPtr prev . 4.14. . . 1. , . 2. . 3. , . cur prev. , prev . , , . , , , . , , .. . , newValue, , . , , newValue, , . , , , newValue. , prev , . , prev , newValue, , (trailing) prev. , , newValue, prev . , prev , . i . / / // . // // ,

prev

prev = NULL cur = head 4.

187

// I/ /I I/ // II

prev , newValue , : newValue , xpaJ4xc , [ , prev (newValue > cur->item) II !

while

{prev = cur cur = cur->next } // while , , , .. ( ), while . while newValue , , NULL. newValue c u r - > i t e m , , NULL. , while , , NULL. , while . while ( NULL newValue > cur->item) i

. // , // . // // prev

prev = NULL cur = head II II II II II II prev cur , newValue , 1 : newValue , , , prev (cur NULL newValue > cur->itemj

while

{prev = cur cur = cur->next } // while , i ^. while ^ . newValue i 11, , , prev , MTLL (. 4.15). , ,

188

I.

newPtr->next = cur; prev->next = newPtr;

head

AI I

prev cur . 4.15. prev , NULL, , prev . NULL, , , . while , prev c u r (. 4.16). , prev NULL. , prev NULL while. , .

-1 head

0prev cur . 4.16. prev NULL, , . . , = head NULL, while . , prev , NULL. , . , , . , , . : , prev . , prev NULLj . 4 . 1 6 .

4.

189

// // // // // // //

: newValue , , , prev

-+

for (prev = NULL, cur = head;

(cur != NULL) ScSc (newValue > c u r - > i t e m ) ; prev = cur, cur = c u r - > n e x t ) ; , & ( "") C++ & , (.. ). , NULL, , c u r - > i tern. , , != NULL . prev ,, , .

, , , , , . , , , . , , , , , . , . -, . , . . . 4.17 . head , .. size . head size . , i cur prev , 5 p r e v . 1 1 -. .

size head

12

3

25

18

Z

. 4.17. , , , I. I prev, find (I),

190

I.

1- . flnd(I) 1- , prev , .. ( I - I j - ? prev, find (I1)7 fund . , prev- > next prev. , I . , head. find i find . - 1 , I . , , . , , . , find , . , . , . , , . . , ( constructor). - (. 3). . , , 3, .// * * * * * * * * * * * * * * * * * * * * * * * * * * * *

// ListP.h // , // **************************

#include ListException.h #include ListIndexOutOfRangeException.h typedef __ ListltemType; class List { public: // : List ; // List(const Listfic aList); // -List ; // // : bool isEmpty const; int getLength const; void insert (int index, ListltemType newltem) throw(LiStIndexOutOfRangeException, ListException); void remove (int index) throw(ListlndexOutOfRangeException); void retrieve (int index, ListItemType& dataltem) const throw(ListlndexOutOfRangeException);

// II 4. 191

private: struct ListNode

//

(ListltemType item; // , ListNode *next; // }; // int size; // ListNode *head;' // ListNode *find (int index) const; // index }; // //

.II ListP.cpp . // . #include ListP.h // #include // NULL #include // assert() // -:

- . . . size head. L i s t : : L i s t : s i z e ( O ) , head(NULL) {} //

size head , . . L i s t . L i s t (const ListS: a L i s t ) ; . , , , , . L i s t y o u r L i s t = myList; , myList . (shallow copying), -. , . , . 192 I.

size size

*1 head /

^

12

3

25

18

7\

head

head

12

3

h->

25

18

^

12

3

[

25

18

Y^om9i

size

head

. 4.18. , . 4.17: ) ; )

3 . , , , , . , , size head. . 4.18, , . 4.17. head . , . , . (deep copying), . 4.18, . , . L i s t : : L i s t (const ListS: a L i s t ) : s i z e ( a L i s t . s i z e ) { i f ( a L i s t . h e a d == NULL) head = NULL; // else

{

// head = newListNode; assert(head 1= NULL); // new head->item = aList.head->item; // ListNode *newPtr = head; // new list pointer // newPtr for (ListNode *origPtr = aList.head->next; origPtr != NULL; origPtr = origPtr->next)

4.

193

newPtr->next = new ListNode; a s s e r t ( n e w P t r - > n e x t != NULL); newPtr = newPtr->next; newPtr->item = o r i g P t r - > i t e m ; } / / for newPtr->next = NULL; } / / i f } / / , . , . , a s s e r t , . , . , , , . . . , .. , . , , () . , , , (compiler-generated destructor), 3. , , , , . (~) . , void, return. , L i s t , , . , remove .List::~List

{while ( isEmpty ) ! remove(1); } //

, . , , . , , d e l e t e . , remove d e l e t e , . . isEmpty getLength . bool L i s t : : isEmpty const {return bool (size == 0) ; } // isEmpty

194

I.

i n t L i s t : : g e t L e n g t h const { return s i z e ; } / / getLength , , . find. . L i s t : :ListNode * L i s t : : find (int index) const //// // // // // . : index . : . index < 1 index , NULL.

// {if ( (index < 1) | | (index > getLength ) ) turn NULL; else //

{ ListNode *cur = head; for (int s k i p = 1; s k i p < index; ++skip) cur = c u r - > n e x t ; return c u r ; } / / if } / / find find NULL index. find . void L i s t : : r e t r i e v e (int index, ListltemTypefic dataltem) const {if ((index < 1) || (index > getLength())) throw ListlndexOutOfRangeException( else

{// , // ListNode *cur = find(index); dataltem = cur->item; } // if } // retrieve . . . void List:: insert (int index, ListltemType newltem)

{int newLength = getLength() + 1;

4.

195

if ((index < 1) || (index > newLength)) throw ListlndexOutOfRangeException( "ListOutOfRangeException: "); else

{// newltem ListNode *newPtr = newListNode; if (newPtr == NULL) throw ListException ( "ListException: "); else

{size = newLength; newPtr->item = newltem; // if (index == 1)

{// newPtr->next = head; head = newPtr;

}else

{ListNode *prev = find(index-1); // , // prev newPtr->next = prev->next; prev->next = newPtr; } // if } // if } // if } // insert . , . . void List: : remove (int index)

{ListNode *cur; if ((index < 1) | | (index > getLength()) ) throw ListlndexOutOfRangeException( "ListOutOfRangeException: "); else

{- -size; if (index == 1)

{// cur = head; // head = head->next;

}else

{ListNode *prev = find(index-1); // , ,

196

I.

// prev cur = prev->next; // prev->next = cur->next; } // if // , cur->next = NULL; delete cur; cur = NULL; } // if } // remove

, , . . , . . , , 3, . , , . , , . , . , , , ? . -, , , ? . , , , , , , . i ? . I : , ? , , , , . , 10000 , 50. , 10000 , 9950 . , , . ? , new , (, , ). , . (, ), . 50 4. 197

. 10000, 12800, .. 2800 , . , . , , 25 . , . . , . , new, . , , . , . . ; , . , , . , , .. . [1] anArray[i-hl]. . . , , , , . , (direct access) . , i t e m s , , , i- , items [i-1]. item[0] item[49] . , (access time) . i- , , i- . , . , , , , .., i- . , , i- , i , 50- . , i- i.

198

I.

. retrieve , . i- retrieve i . , . , , 20 , 19 . , i-ro , size, size-i . , size-1 , . insert . , . , insert removej . . , , . , - find. find, , find(i) i . , , find(i), . . 3 , .

, . , . , . . s t r u c t Node{ int item; Node *next; }; // Node *head;

- i ^ , i , : ? , , .. , . , . , , , . ^ , 4. 199

, . , . , , . , , , . , , . . 4.19. ( .) ( ) +4-.// , . // . // fileName ofstream outFile(fileName); // , // for (Node *cur = head; cur != NULL; cur = cur->next) outFile item next = new Node;

1 2

n e x t . , . , , tail, head, NULL. , , . , new , . // // // // // , , . head t a i l NULL. fileName

4.

201

ifstream inFile(fileName); int next I tern; if (inFile >> nextltem) // ?

{// : head = new Node; // head->item = nextltem; head->next = NULL; tail = head; // while (inFile >> nextltem)

{ t a i l - > n e x t = new Node; t a i l = tail->next; t a i l - > i t e m = nextltem; t a i l - > n e x t = NULL; } / / while } / / i f inFile.close(); // // // // : head , t a i l - . , head and t a i l NULL ( ) .

, head t a i l . , inFile , . , , . linkedListInsert, . head = NULL I while (inFile >> nextltem) linkedListlnsert(head, nextltem) (insertion sort). 9. save restore, , .

I , ,

? . , . , , head L i s t . - head . head ? , - Link , 202 I.

. , , , head - , . , . . . , , , . : ? , , . , headPtr , , , , headPtr. , . , , . . 4.22 , head headPtr, . , - , , . , , , ," "

head

2

4

6

>

86

headPtr" "

. 4.22. , , , , , , , head . , , head . , head. , , headPtr, head, headPtr, , headPtr !

, , . , . , , , . . , . 4. 203

, .struct Node

,

{char item; Node *next; }; // Node *stringPtr;

stringPtr , . , . , , , , . . 4-+.

void writeString(Node *stringPtr) //// // // // // // . : , stringPtr. : . stringPtr .

{if (StringPtr != NULL)

{// cout item; // writeString(stringPtr->next); } // if } // writeString

. . writeString , StringPtr, . , , . StringPtr , stringPtr>next . writeString , . , . 2 . , writeBackward ;. writeBackward2 . . 204

I.

, , . , , . , stringPtr , ? , , , , . , . ( , .) , , , , writeBackward2 , . , , writeBackward writeBackward2 , . writeString. StringPtr, , StringPtr>next . . void writeBackward2(Node //// // // // // //

*stringPtr)

. : , stringPtr. : , . stringPtr .

// {i f ( s t r i n g P t r != NULL) { / / / / writeBackward2(stringPtr->next); / / cout i t e m ; } / / if } / / writeBackward2 8, , . -, . 2.9. 5 . ? . , , . . , . , , , , . . 4. 205

, head, , head NULL ( ) head->next NULL ( , , ), head-'>item < head->next->item, head->next . . , , , , , , . . void l i n k e d L i s t I n s e r t ( N o d e *& headPtr, ItemType newltem) { if ((headPtr == NULL) || (newltem < headPtr->item)) { // : newltem // , // headPtr Node *newPtr = new Node; if (newPtr != NULL) throw ListException ( "ListException: "); else { newPtr->item = newltem; newPtr->next = headPtr; headPtr = newPtr; } // if } else l i n k e d L i s t l n s e r t ( h e a d P t r - > n e x t , newltem); } / / l i n k e d L i s t l n s e r t linkedListlnsert , , . headPtr = newPtr; - i headPtr , next - 1 . - I , headPtr . , newPtr, headPtr. , ? , ^ headPtr . , , , head. . , (newltem == headPtr->item), 206 I.

, headPtr, headj . 4.23, . , headPtr , headPtr = newPtr head (. 4.23, ).headPtr

head

I

)

2

-

4

6

newPtr . 4.23. : ) ; ) , , head, . , headPtr ? n e x t , . , next , newltem. , headPtr , headPtr = newPtr next . . 4.24 . linkedListInsert, , 3 . sortedlnsert (newltem), newltem . sortedlnsert . linkedList Insert . linkedList Insert . , linkedListlnsert 4.

207

. . . (. 2.) ( , ), , , 10.headPtr

head headPtr

head headPtr head

newPtr

. 4.24. : ) linkedList Insert (head, 3); ) ; ) , , headPtr,

, , . . . , . , . Person^ , , , . .

208

L

typedef Person ItemType; struct Node{ ItemType item; Node *next; }; //

, ,

Node *head; typedef . ,

. , . . , , , , , , . .

, , , , (server). , , . , . , . , , . , , , . , ? , . . . , . , NULL . (circular linked list), . 4.25. , , , (linear).

1

^

*~"

4

I

*

8

^ list

J

. 4.25.

4.

209

, , . , , . - . , - , . "" , , , , , . , l i s t "" , . 4.26, , , list->next .

b

g

m

w

list

(1

1

J

. 4,26. NULL, , . , , NULL. , . , list. , , , , , , l i s t , , , . / / , 1 , / / ; 1 / / l i s t L----------------^^ / / i f ( l i s t != NULL) {// , Node *first = list->next; // Node *cur = first; // // : cur // , do

{ d i s p l a y ( c u r - > i t e m ) ; / / cur = c u r - > n e x t ; / / } while (cur != f i r s t ) ; / / ? } / / i f .

210

I.

. , . (dummy head node), . 4.27. , . . , prev , NULL, , , , prev->next = c u t - > n e x t ; , , , . 1head

44

Z

. 4.27. , . .

, . , , . , , . (doubly linked lists), , . , , , , precede next. , next N , N . precede , N . . 4.28.^ Able

|J J Smith 1

|< 4- J Wilson^

1 (

head

. 4.28.

4.

211

N, prev = c u r - > p r e c e d e ; , , . , , . , , , . , , . . 4.29, , listHead . : precede n e x t . , (circular doubly linked list) . n e x t , , " " , precede, " " , , . , precede, , , n e x t . , . , . 4.29, .listHead

1A

1 1

->

Baker

-precede)->next = c u r - > n e x t ; (cur->next)->precede = cur->precede , , , : , . , , , , , -> . . , , , . , , . , , , , , newName ( "" . . .). , . / / / / = listHead->next // , while ( listHead newName > cur = cur->next |

cur->item)

, . . 4.31, , . 4. 213

1. 2. 3. 4.

next . precede . precede . next .Baker Smith

newPtr

. 4,31. ; +- ( , newPtr ). / / , 1 / / newPtr, ^ " "" '" ' ' '" ' '/ / , cur newPtr->next = c u r ; newPtr->precede = c u r - > p r e c e d e ; cur->precede = newPtr,newPtr->precede->next = newPtr, , , , : ( c u r ), ( ).

: , . , , , , . . : , . : , . ( , .)

: , . , . , . 214 I.

, . , . (. D.) , , . , . ( , : , .) . .I ,

l L A

M D

R

S

Q

, ( ) , , , ( ) . , , , , . , , , , . 1. , .

4.

215

, , . 1. . 2. . 3. . , . . , . , . . . ( L). ( I, , D, S). , ( , D, R S). ( D). , , ( S). , , ( D). , , ( I L). ( Q). . " ". . , . , . , , , . ? , , , . , . , , . , , , . 4.32, . 216 1.

)

title have

_*

who

want waitHead waitTail next next

. , . . template c l a s s MyClass { public: MyClass(); MyClass(T i n i t i a l D a t a ) ; void setData(T newData); T getData(); private: T theData; }; 8. , , . , , . i n t main {MyClass ; MyClass b(5.4);

= < > \ < >< >< > < > = + | - | * | / < > = | | . . . | Z . 1, , . , , . < >< >< > , . . . , . ? : , , . , , , , EY . . 14. , , EY . . , . 248 I.

endl, , endl+1. , , . , , ^-/ab-cd . +12, Ei . : El = /34, = 4 = 4 , Ei . 2 = -, = = d

, . StrExp, , , , . endPre (first) J , first strExp. , endPre - 1 . . +endPre(in first: integer) // , . // : strExp, // first , . // : // , first // StrExp. // , endPre -1. last = StrExp.length - 1 if (first < 0 first > last) return -I ch = , first StrExp if (ch ) // // return first else if (ch ) { // firstEnd = endPre(first+1) // X // // if elsereturn -I

, (firstEnd > 0) return endPre(firstEnd+1) // Y if

} // else return -1

5.

249

. 5.5 endPre +/ab-cd. endPre , strExp . e n d P r e :

+, X e n d P r e : first = last = X: e n d P r e ( 1 )

f ir'it

'-'''''''-' Wyiiif,

li' "''

'"; '

/, X e n d P r e : first = last = X: endPre(1) first = 1 last = X: endPre(2)

I'-f ir^e-'^/: ' -^-,/:''^;,; -':/: /'VV ^;f i r B t B t i ^ ' / ' ;l;:;Ksr';,2^'-''-"'''"/'".^.''{'-'

first last return 2

= 2 =

I I f i r s t E n d > - l , Y e n d P r e : first last X: endPre(1) first = 1 = 6 last = 2 firstEnd Y: e n d P r e ( 3 )

. . e n d P r e : first = last = X: endPre(1) 'tXtpt. ' ",'' \%, '//'"?': Z ,7/V I'firbtib^V '-'/' / ?

1 'ret'mrii;!3^,\: '''^'''/''-, e n d P r e :

S'V'''X\ \ 'z\

j first I last I return 3

-'first '" riaj^t

:'\', .0 ;//:"' ' '] %\ f'I'rstltid'' '-, -'

1" ' ^ / - ' ^

first last firstEnd return 3

= 1 = = 2

250

I.

f i r s t E n d > - l , Y endPre: first = 0 last = 6 firstEnd = 3 Y: endPre (4) -, X endPre:

= o| first last = 6 firstEnd = 3 Y: endPre (4)

first = 4| last = 6 X: endPre(5)

. . endPre : first = 0 last = 6 firstEnd = 3 Y: endPre(4) first last return 5

f i r s t E n d > - l , Y endPre: first = last = 6 firstEnd = 3 Y: endPre (4)

o l

first = 4| last = 6 firstEnd = 5 Y: endPre()

.' i-'.T", J'"

\ ',"'-':>''^/'- . ''"-/ >': 1 '^,-Z''

d. . endPre : first = 0 last = 6 firstEnd = 3 Y: endPre (4)

first last return 6I

endPre : first 1 last 1firstEnd j return 6 = 4 = 6 = 5

"fi';-

endPre , a endPre:

I first I, I last IfirstEnd I return 6

= 0 = = 3 endPre(O), strExp

. 5.5. -\-/ab-cd

5.

251

// , // . // : // // // //

i L.,.,,,.,.,,. , ................ ,

strExp, . : true, ; false. = endPre(O) >= 0 and lastChar == strExp.length ()-1)

lastChar return

(lastChar

, . ? , . , . , , . , . , . evaluatePrefix (in strExp: string) : float // strExp. // : strExp , // . // : . ch = strExp strExp If (ch ) // return else if (ch op) { operandi = evaluatePrefix(strExp) operand2 = evaluatePrefix(strExp) return operandi op operand2 } // if , e v a l u a t e P r e f i x StrExp , . C + + , strExp . , , . . , . < > = < > \ < >< < > = + | - | * | / < > = || . . . | Z >< >

. , . . 6. -

252

I.

. , . . , postfix(exp) = . < prefix2> : < postfix2> , < prefix2> . , postfix(exp) = postfix{prefixl)+ postfix(prefix2)+ . if ( return else return postfix (prefixl) ) + postfix (prefix2) + i | ^

convert. pre , post . convert pre , , , , convert. evaluatePrefix, pre . p o s t . convert (in pre: string, out post: string) // : pre // . // : post // . // ch = pre pre

if (ch ) // // post = post+ ch // post else //{

ch

// convert(pre, post) // convert (pre, post) // post = post+ ch // } // if

5.

253

, . , . , . , , . , , , . < > = < > \ < >< >< > < > = + | - | * | / < > = | | . . . | Z , . , . , . 7, , , , . , , 6.

. , , . , , , 1. , , , . , , , . ? , , , , . , , 2, . , , . , , 2 2^^-! , N .

254

I.

, , , ,

fact (in :integer):integer if (n is 0) return 1 else return n * fact (n - 1), fact fact (0) = ! = 1 fact(n) = ! = * ( - 1) * ( - 2) * ' ' * I , > .

. . , = , , , fact (0) 1. : fact (0) 1 . . k, k+1. . n=k. , ,

fact () = ! = * ( - 1) * ( - 2) * - * 1 . , , , fact(k+l) n=k+l.

= (+1)! = ( + 1} * * ( - 1) * ( - 2) - * 1

fact fact fJc-flj (+1)* fact () , fact () * ( - 1) * ( - 2) * ' - * 1 , fact (+1) ( + 1) * * ( - 1) * ( - 2) ' * 1, . , . k, k+1. .

5.

255

2 . solveTowers(count, if source, destination, source spare)

( count 1) destination

else{ solveTowers(count-1, source, spare, solveTowers(1, source, destination, solveTowers(count-1, spare, destination, } // if destination) spare) source)

: N , , ? moves (N) , N . N = 1 . moves(1)=1 N > 1, moves (N) . solveTowers , . , , N-1 , . . moves ) = moves - 1) + moves (1) + moves (N 1)

, , ^ . moves(1) = 1 moves (N) 2 * moves(N , moves (3) = 2 * moves (2) - 1 = 2 * (2 * moves(1) + 1) + 1 = 2 * (2*1 + 1) + 1 = 7 - 1) + 1,

, so/veTowers N

N > 1

moves (), (closed-form formula), , , N . , . , . . moves(N) 2 - 1 N > 1 solveTowers N

, 2 - 1 7, moves(3).

256

I.

, moves(lSf)=2^-1 . . , N=1, 2^-1=1 moves(l)=ly . , k, k+1. . , N=k, , , moves () =2^-1. . , N=k+1. , , moves(k-\-l)=2 ^ 1 - 1 . moves fie -hi) =2 * moves () + 1 = 2 * (2^ - 1) + 1 = 2^^' - I , . : k, k+1. . , . . , . .

1. , . , , , . , , , . , . , . . . , . , , , . , . . . , , . 257

2.

3.

4.

5.

, , . . , , . , , . , . , , , . . . , 1 .

1. . , , 4x4. , . (a/b)*c-{d+e)*f . {a*b-c)/d+{e-f) . -a/b+c*def . +-/abc*+def*gh ? , : $, cc$d, cccc$dd, cccccc$ddd .. .

2. 3. 4. 5. 6.

1. . 1.1. isPal abcdeba, 1.2. isAnBn . 1.3. endPre -*/abcd. , . =$||$ =abbIabb , , . , . . , . , , . , . I.

2.

3.

4.

258

5.

6.

7. 8. 9.

, . , . . , , . : \\ =* =5.1. , . 5.2. ? . 5.3. , , , . , . 5.4. isln(str) . t r u e , str , false . L , . ={ S, "^", >0} , L, , . , L, , . 6.1. L. 6.2. , strExp L. +*a-b/c++de~fg ? , . ab/c*efg*h/+d ? , . , .

- I =A|B =:l|2 9.1. , . 9.2. , . 10. , : ; ; ; , , ; D, , . , : , , , DCA, , , , DB DCCB. 10.1. . 10.2. CAB? . 10.3. , . 5. 259

11.

, . = $|||...||2 , ={ u;$reverse(u;), w } , . , . , . , str , . . , , , $. , , ( str) . , . C++, . .int (int )

12.

{if ( < 3) return X; else return p(x-l) * (-); } //

{) , {). 12.1. ( ) . 12.2. . 13. , , , "" "", "", "" "101". {) . 13.1. (). 13.2. . 14. : , Y , EY . {: .) 15. 2 c{n,k), . 260 I.

1,/ = , 1, k = , {, k) = , / > , [( - 1, ^ - 1) -f ( - 1, k)y < k < . , , c{n,k) 1 (n-k)lkl

1. 2. , . , , . 3.1. ? , ? 3.2. isUnderAttack? 3.3. placeQueens? 3.4. isUnderAttack? , , , ? , . placeQueens, . . , . 8x8 , , . col , , col [] = , {-\-1)- . , col [2] 4, , .. board[3] [2], , col [], board [col [] -1] [], , . , . rowAttack, rowAttack [] , , (:-1)- , , . , . , , , . , . , board [1] [j] , 261

3.

4.

5.

5.

i+j , , i-j . , i+j 14, 1-j - 7 +7. , posDiagonal negDiagonal, posDiagonal [] t r u e , , (:4-1)- , , ; negDiagonal [] true , , (+1)- , , . , . , ? , ! , , , . . , , . X X X X X XX X X XX X X X XX XX X X XX X

, , . , : , , . , , , . , , . , . . : ( ), ( ), ( ) ( , ). , . "" , . , , , . "" , . , , , . . . , , , . 262 I.

"" , ; ; , .. . , , . , , . . 20 7 ^>>'^>>^^ , . 2. , . 3. . , Q 2, 2 Q. , , . , . , , . , . 6.10 , Q, . , , , . , Z . 6.10 , , , . , , R, R X, ( 2). W. W S, W. W ( 3). , , , , . , , . , , . , . , 6. 297

. , , (backtracking). , , . , , . , . , , . . 6.10. Z , i^, X. X , R, X. , - , X. , . , , R. W, ! , , , . , , . , . , - , , . 6.11, -. , , . , (, ), , . 6.11, . , . . 6.11, , W,X R

)

R )

)

R

)

W )

. 6.11. : ) ; ) R; ) X; ) R; ) ; ) W . aStack.createStack() aStack.push(originCity) while { if else{

aStack ( )

// //

( , ) aStack.pop () ,

298

II.

aStack.push () } // if } // while , . , , , , , , .. , . , while . 1 , , , . , , . . , -, , , , . -, . , : , , . , , , . . , .. , , . , Q, 2, ..., , , ', , . , , . 6.10, , , IV, S . W, / . W S, S , VJy , S . W, S W, . . 6.12 : , , . , , , . . , . , , 299

6.

MLi^SJ^

W

')

)

. 6.12. : ) ; ) , . , , . 6.10, i?, X, X . , X , , , . , , . , . , . , , . 6.10. : R, X, R ( X ), ( ), W, . P-VJ-Y^ , . 6.12, . , R , , . . "" '' , . , , , , . .I " while ( )

300

II.

// : // , , // , if else { , , , aStack.push() ] // if } // while while, .. , " ". 1 , ,, , , , , , , . , , .. , . , . +searchS (in originCity:City, I in destinationCity:City):boolean I / / ' < "~^- "' " """" '""" "'"-,-. " " / / aStack.createStack() aStack.push(originCity) ( , , ) aStack.pop () //

// // while { // // // if : , , , (laStack.isEmpty )

] //

( , , ) aStack.pop () // else { , , , aStack.push() } // if while

.

301

if

(aStack.isEmpty()) return false // return true //

else , . , : , . , . , , . , , . 6.13. , Z. . R X PopR W S Pops Y Z , , , , , , , , , , , , , , , ( )

PR PRX PR PW PWS PWST PWS PW PWY PWYZ

. 6.13. , . 6.10 , . , , , . , , . , , , . +createFlightMap() I / / """" "'" ....,......, ,....,.,, +destroyFlightmap() / / -HreadFlightMap (in cityPileName: s t r i n g , in flightPileName:string) / / +displayFlightMap() / / +displayAllCities() / / , / / +displayAdjacentCities(in 302 aCity:City)

II.

// , // +markVisited(in aCityrCity) // +unvisitAll // +isVisited(in aCityiCity) rboolean // , +insertAdjacent(in aCityzCity, in adjCity:City) // +getNextCity(in fromCity:City, out nextCity:City) rboolean // , , // , .. // . true, // , , // false +isPath(in originCityrCity, in destinationCity:City)iboolean // , // , isPath searchS. , Stack , Map . . bool Map: : isPath (int originCity, int | searchS C++ destinationCity) // // , // . . // : originCity destinationCity // . // : // originCity destinationCity , // true; false. // , , . // 1: , // . unvisitAll, // markVisited getNextCity. // Stack aStack; int topCity, nextCity; bool success; unvisitAll0; // // // . aStack.push(originCity); markVisited(originCity); aStack.getTop(topCity);

6.

303

while (laStack.isEmpty

&& (topCity != destinationCity))

{// : // , , // , // , // success = getNextCity(topCity, nextCity); if ( !success) aStack.pop(); // ! else //

{aStack.push(nextCity); markVisited(nextCity); } // if aStack.getTop(topCity); } // while

if

(aStack.isEmpty0) return f a l s e ; / /

elsereturn true; / / } / / i s P a t h , 9, " ".

, . Q , . , Q. Ci , ; , Q. 2. , 2 ; , , .. . i . 1.. , ., ., .. . ..,. . ,. .,. ,. ,... . . .-..,., , ,., , .,. ., ,. ,,..,.-,-,.., , , if ( )

else . . , .

304

II.

, . . 1. , , . 2. , . 3. . . , , . , , , .. . , . ( , , .. .) , , . , , . , . +searchR(in originCity:City, in destinationCity:City) -.boolean // // originCity destinationCity.

If

( originCity ) else for ( ) searchR(C, destinationCity)

, , , . , . 6.14. searchR X, .. originCity X, for , X , . , searchR . )V, X. , , , searchR (X, destinationCity), for, , W, .. o r i g i n C i t y W. X W for . , searchR (V, destinationCity), , W. W f o r , W , . searchR, . 6. 305

I Y ()

* 1 ()

()

V

. 6.14. W, , , , , . , , , . C++, - i searchR searchR. | C++ bool Map::isPath(int originCity, int destinationCity) { int nextCity; bool success, done; // markVisited(originCity); // : if (originCity == destinationCity) return true; else // { done = false; success = getNextCity(originCity, nextCity); while (success && !done) { done = i s P a t h ( n e x t C i t y , d e s t i n a t i o n C i t y ) ; i f (Idone) success = g e t N e x t C i t y ( o r i g i n C i t y , n e x t C i t y ) ; } / / while return done; } / / i f } / / i s P a t h , searchR searchS. . .

306

II.

, . , . , . , , , . . . searchR , searchR (, destinationCity), searchS , . searchR (, destin^tiqnCity) -, o r i g i n C i t searchR. , . 6.15 searchS Z (. . 6.10). . , . , originCity ( ) searchR, , searchS, , , . searchR . - . searchS , . , , . 6.15, R, (. 6.16). . , . , , . searchR , . searchS .originCity = destinationCity =Z ) originCity =R destinationCity =Z

X -next = NULL; 2. backPtr->next = newPtr; 3. backPtr = newPtr; 4 1 7

// l /

I

1 () 1frontPtr

0backPtrn e w P t r ( )

. 7.5. )) II |,

'frontPtr

frontPtr

7\

frontPtr = newPtr; backPtr = newPtr;

IZI

backPtr newPtr newPtr . 7.6. : ) ; )

backPtr

1. 2. 3. 4.

tempPtr = frontPtr; frontPtr = frontPtr->next; tempPtr->next = NULL; delete tempPtr;

tempPtr

"t P t r fron

backPtr

. 7.7.

II Q u e u e P . h . / / .// ************************************

#include "QueueException.h" typedef -- QueueIt; class Queue { public: // : Queue ; // Queue(const Queue& Q); // -Queue ; // // Queue: bool isEmptyO const; // , . // : . // : , // true, false.

326

II.

void enqueue (QueueIt newltem) throw (QueueException) ;' ' // // : // newltem. // : , // newltem . // : newltem // , // QueueException. void dequeue throw(QueueException); // // Precondition: None. // : . // : , // , // : , // QueueException. void dequeue (QueueltemTypeSc queueFront) throw(QueueException); // . // : . // : , queueFront // , . // . // : , // QueueException. void getFront(QueueItemType& queueFront) const throw(QueueException); // . // : . // : , queueFront // , . // : , // QueueException. private: // // struct QueueNode

{QueueltemType item; QueueNode *next; }; // QueueNode *frontPtr; QueueNode *backPtr; }; // // . newltem , , , . .

7.

327

/I QueueP.cpp . // . #include "QueueP.h" // #include #include Queue::Queue() : backPtr(NULL), frontPtr(NULL)

{} // no Queue::Queue(const Queued Q)

^ {// ( 4 ) . } // KoiiCTpyKTopa Queue::-Queue() { while (!isEmpty) dequeue(); // : frontPtr backPtr // NULL } // bool Queue::isEmpty const

{return bool(backPtr == NULL); } // isEmpty void Queue::enqueue(QueueltemType newltem) { // QueueNode *newPtr = new QueueNode; if (newPtr == NULL) // throw QueueException( "QueueException: enqueue "); else { // ; // newPtr->item = newltem; // insert the new node if (isEmpty 0 ) // frontPtr = newPtr; else // newPtr->next = backPtr; backPtr = newPtr; // // } // if } // enqueue

328

.

void Queue::dequeue()

{if (isEmpty()) throw QueueException( "QueueException: dequeue "); else

(// . . QueueNode *tempPtr = frontPtr; if (frontPtr == backPtr) // ?

{// , frontPtr - NULL/ backPtr = NULL;

}else frontPtr = frontPtr->next; = tempPtr~>next = NULL; // delete tempPtr; } // if } // dequeue void Queue: .-dequeue (QueueItemType& queueFront)

{if (isEmpty0) throw QueueException( "QueueException: dequeue "); else

{// . queueFront = frontPtr->item; dequeue(); // } // if } // dequeue void Queue::getFront(QueueltemTypeS: queueFront) const

{if (isEmpty()) throw QueueException( "QueueException: getFront "); else // . . queueFront = frontPtr->item; } // getFront // . , , . #include "QueueP.h" int main

{Queue aQueue; aQueue.enqueue(15);

7.

329

, . . 7.8, , ; . const i n t MAX_QUEUE = -; typedef -- QueueItemType; QueueltemType items[MAX_QUEUE]; int front; i n t back;

2

4 1 2

1

7 j3 items

'''/7''l''kPi'"^^'^{"4''t ;/

if]-

front

back

0

MAX_Ql

6)

47

49

^47

1048

2

front

back

49

1_

MAX QUEUE - 1

Puc. 7.8. : ) ; ) front back . front , back - 1 . , back items [back]. , front. , back f r o n t . , back MAX_QUEUE-1, (rightward drift). , . , back MAX_QUEUE-1, . . 7.8, . , , . , back MAX_QUEUE-1, , , MAX_QUEUE . , .

330

II.

, , . 7.9. front ( ) back ( ) . . 7.10 f r o n t , back . front back MAX_QUEUE-1, . , . , . . front back.

, , front back. . 7 . 1 1 , . , : , back front. . 7 . 1 1 , . , . , , . , MAX_QUEUE. , . , . , . frontMAX_QUEUE

back

. 7.9.

9

MAX_QUEUE - 1

Q

front

MAX_QUEUE - 1

MAX_QUEUE - 1

back

back

back

. 7.10.

, . 7.9

7.

331

-

MAX_QUEUE - 1

MAX_QUEUE - 1

front

MAX_QUEUE - 1

MAX__QUEUE - 1

)

front back

front back

. 7.11. : ) , front back; ) back front front , back MAX_QUEUE-1, front back (.. %, C-f-f). , newltem . b a c k = (back+1) % MAX_QUEUE; i t e m s [back] = n e w l t e m ; + -fcount ; I *"' "" ' "" " "' """" """ " '-""...-..,.-,.,., "

newltem back MAX__QUEUE-1, , b a c k = ( b a c k + 1 ) % MAX_QUEUE, bacJc . f r o n t = ( f r o n t + 1) % MAX_QUEUE; - - count; | * """ " ' '""" ' '""'" "'"'""'

C-f. , .^ , .

332

II.

- . . /I QueueA.h . // . #include "QueueException.h" const int MAX__QUEUE = --; typedef -- QueueltemType; class Queue

{public: // vi : Queue 0 ; // no // // // Queue: bool isEmptyO const; void enqueue(QueueltemType newltem)3 throw(QueueException); void dequeue() throw(QueueException); void dequeue (QueueItemTypeS: queueFront) throw(QueueException); void getFront (QueueltemTypeSc queueFront) const throw(QueueException); private: QueueltemType items[MAX_QUEUE]; int front; int back; int count; } ; // Queue // .// *********

// // // ////

QueueA.cpp . . . .*************

#include "QueueA.h" // header file Queue: :Queue 0 :front(0), back(MAX_QUEUE-1) , count(0)

{} // bool Queue::isEmpty() const { return bool(count == 0 ) ; } // isEmpty

7.

333

void Queue::enqueue(QueueIt newltem) { if (count == MAX__QUEUE) throw QueueException( "QueueException: enqueue "); else { // . // back = (back+1) % MAX_QUEUE; items[back] = newltem; ++count; } // if } // enqueue void Queue::dequeue() { if (isEmptyO) throw QueueException( "QueueException: dequeue "); else { // . , front = (front+1) % MAX_QUEUE; --count; } // if } // dequeue void Queue::dequeue(QueueItemType& queueFront) { if (isEmptyO) throw QueueException( "QueueException: dequeue "); else { // . queueFront = items[front]; front = (front+1) % MAX_QUEUE;--count;

} // if } // dequeue void Queue::getFront(QueueItemType& queueFront) const { if (isEmptyO) throw QueueException( "QueueException: g e t F r o n t " ) ;

else/ / . queueFront = i t e m s [ f r o n t ] ; } / / g e t F r o n t / / . , , . 334 isFuil

II.

, is Full, is Full , . , items MAX__QUEUE+l , MAX_QUEUE . , , front , . . 7.12, , , front back front (-1) % (MAX_QUEUE+1)

front

back

) ) . 7.12. : ) ; )

isFully . 1 , , is Full (?). , . 3 4.

, , , . 7.13. , , , dequeue remove (1), getFront (queue front) one- retrieve (1, queuefront), , 2 4 17 , enqueue (newltem) 1 2 3 4 insert (getLengthO+1, . 7.13. newltem).

7.

335

3 4 List. , , List. .// * * * * * * * * * * * * * * * * * * * * * * * *

// QueueL.h . // .// ************

#include "ListP.h" // #include "QueueException.h" typedef ListltemType QueueltemType; class Queue { public: // : Queue{); // Queue (const Queue&r Q) ; // -Queue ; // // Queue: bool isEmptyO const; void enqueue(QueueltemType newltem) throw(QueueException); void dequeue 0 throw(QueueException); void dequeue (QueueItemTypeS: queuePront) throw(QueueException) ; void getPront (QueueItemType&: queuePront) const throw(QueueException); private: List aList; // }; // queue // .// **********

// QueueL. . // .// *************************

#include "QueueL.h" // Queue::Queue() { } // Queue::Queue(const Queued Q ) : L(Q.L) { } // Queue::-Queue() { } // bool Queue::isEmpty() const { return (aList.getLength0 == 0 ) ; } // isEmpty 336 II.

void Queue: .-enqueue (QueueIt newltem) { try , { aList.insert(aList.getLength()+1, newltem); } // try catch (ListException e) { throw QueueException( "QueueException: "); } // catch } // enqueue void Queue::dequeue() { if (aList.isEmpty()) throw QueueException( "QueueException: dequeue else aList.remove(1); } // dequeue

");

void Queue :: dequeue (QueueltemTypeSc queueFront) { if (aList.isEmpty0) throw QueueException( "QueueException: dequeue "); else { aList.retrieve(1, queueFront); aList.remove(1); } // if } // dequeue void Queue::getFront(QueueItemType& queueFront) const { if (1aList.isEmpty()) throw QueueException( "QueueException: getFront "); else aList.retrieve(1, queueFront); } // getFront // . , . , , .

queue STL STL queue, Queue, . gueue , 7. 337

push pop, stack. , . queue . STL front, get Front, queue , Queue. back, , size, , . gueue . template < c l a s s , c l a s s C o n t a i n e r = deque > c l a s s queue { public: explicit queue(const Container& cnt = Container()); // no , . // : . // : . bool empty() const; // , . // : . // : , // true, false. size_type size() const; // . size_type // . // : . // : . &front ; // . // : . // : . &(); // . // : . // : . void pop(); // . // : . // : . void push(const & ) ; // . // : . // : } // queue STL

338

II.

queue, stack, . , , (adapter container). , . STL , : vector, list deque, list 4. vector . deque (double-ended queue), , . , . stack gueue . , queue l i s t STL. , vector , , stack . stack gueue queue , deque degue. , queue myQueue; myQueue, degue. , l i s t , .queue myQueue;

myQueue, list. , , . , .#include #include #include #include using namespace std; int mainO

{list myList; // list::iterator i = myList.begin(); for (int j = 1; j < 5; j++)

{i = myList.insert(i, j ) ; i + +; } // for

7.

339

cout , . , . , , . i n t main {NewClass first; NewClass second(4.8);

first.setData(5); cout newLength)) throw ListlndexOutOfRangeException( "ListOutOfRangeException: insert "); else

{// newltem 11|||||||1 *newPtr = new ListNode; _...._ ^ i^ubi,) throw ListException( "ListException: insert " ) ; else

{size = newLength; newPtr->item = newltem; // if (index == 1)

{// newPtr->next = head; head = newPtr;

}else

{ *Pi^ev = find(index-l) ; // , // prev newPtr->next = prev->next; prev->next = newPtr; } // if } // if } // if } // insert jjljil^iSlI *List: :find(int index) const if ( (index < 1) | | (index > getLengthO) ) return NULL; else //

{ ! *cur = head; for (int skip = 1; skip < index; ++skip) cur = cur->next; return cur; } // if } // find

390

II.

, 4, insert . void L i s t : : i n s e r t ( i n t index, ListltemType newType); . void L i s t ^ | : : i n s e r t ( i n t index, T newltem)

List

L i s t template voidy , ListltemType . , , , . #include " L i s t T . h " i n t main {

List f l o a t L i s t ; List c h a r L i s t ; floatList.insert(1, floatList.insert(2, charList.insert(1, charList.insert(2, 1.1); 2.2); 'a'); 'b');

, floatList charList . , , . , . , . , , . , , :template

, .

1. , , . 2. . 3. . 4. .

8. 4-+

391

C++ . 2 + 3 2. +3.0 , . , , 2 3, , 2.0 3.0, . C++ , . + . , , (overloaded) . C++ i . - I ^ . L ^ .,,. . , , C++, . - , , .. . , myList yourList L i s t , .if (myList == yourList) cout next; } // for isEqual = count > size; } // if return isEqual; } // operator==

, == . - , , , ==. (next; return *this; } // operator++ bool Listlterator::operator==(const ListIterator& rhs) const { return ((container==rhs.container) && (cur == rhs.cur)); } // operator == bool Listlterator:roperatorl=(const ListIterator& rhs) const ( return 1(*this == rhs); } // 1=

L i s t , Listlterator, , , . , .// * * * * * * * * * * * * * * * * * * * *

// Listl.h . // Listlterator.// ***********

#include "Listlterator.h" 8. C + + 397

#include "ListException.h" class List { public: // : List ; List(const List& aList); -List 0 ; // : bool isEmptyO const; int getLengthO const; Listlterator insert(Listlterator iter, ListltemType newltem) throw(ListException); // , // iter. // , . // : iter // , . // : iter , // end(), newltem // . , // newltem. // : // , // ListException. void retrieve(Listlterator iter, ListItemType& dataltem) const throw(ListException); // . // : iter . // : dataltem // . // : // , // ListException. Listlterator remove(Listlterator iter) throw(ListException) // , // , . // : iter . // : , , // . , , // . // , , // endO . // : // , // ListException. Listlterator begin() const; // , // . // : .

398

II.

// : , // . , , // end(). Listlterator end() const; // , // , // . // : . // : . private: int size; // ListNode *head; // ListNode *findPrev(Listlterator iter); // , , // . // : (head 1= NULL). // : , // , . iter == end(), // . }; // - begin , . end , , . , List, Listlterator, #include "Listl.h" #include using namespace std; int mainO

{List aList; Listlterator i = aList.begin(); for (int j=l; jnext = newPtr; } // if } // if return Listlterator(this, newPtr); } // if else throw ListException( "ListException: insert "); } // insert 14, .

400

I. I

. , , , , . - ( ). - ( ) , . 2. , , . . , . "" ("is-a"). 3. - - , . - - , . 4. - , . - , , . . 5. . . 6. , , . , , , . 7. , , , . , , . 8. , , spherePtr->displayStatistics (), , . 9. , , . 10. , C+-f, , . , , . 11. . 1.

8. +-

401

1. 2. - , . . - , , . , . , , . , "". , , , .

3. 4.

Sphere Ball, " ". 1. C-f + , . 1.1. Sphere Sphere, 2. 1.2. myBall Ball, , 6, Beach Ball, 1.3. Sphere myBall, 2. Planet, Ball, . , , -, . 3. . 3.1. resetBall, Ball, - theRadius , resetBall Sphere? . 3.2. , theRadius , Sphere, ? 4. ACR VCR, " ". ACR , VCR? 5. SortedList, . , aList , . SortedList, , SortedList? . 6. , BasicADT, . aList , isEmpty getLength? . 402 II.

7. 8.

- ? , NewClass " ", . - myClass ' ' . , myClass.

1. Sphere Ball, ", c l a s s Sphere { "

public:double getAreaO const; // void displayStatistics0 const; }; // class Ball: public Sphere { public: double getAreaO const; // void displayStatistics() const; }; // , displayStatistics g e t Area. 1.1. mySphere Sphere, myBall Ball, get Area . mySphere.displayStatistics(); myBall.displayStatistics(); 1.2. Sphere * s p h e r e P t r ; Ball *ballPtr; spherePtr ballPtr, get Area ? . spherePtr->displayStatistics(); SpherePtr = &:myBall; SpherePtr->displayStatistics(); ballPtr->displayStatistics() ;

8. C+4-

403

2.

3.

4.

, Ball . , , color - isEmpty write. " " Equidistant Shape, - theRadius, 3.1. Sphere, Equidistant Shape. ? 3.2. , Equidistant Shape. 3.3. Equidistant Shape , theRadius , . , ? 3.4. 3.1 3.2, , 3.3. .class Expr

{public: int getLengthO const; virtual void display() const; private: char Array[MAX_STRING+1]; }; // class AlgExpr: public Expr

{public: bool isExpression0 const; bool isBlank(int first, int last) const; }; // class InfixExpr: public AlgExpr

{public: bool isExpression0 const; int valueOf0 const; void display 0 const; protected: int endFactor(int first, int last) const; int endTerm(int first, int last) const; int endExpression(int first, int last) const; private:

404

II.

Stack values; Stack operators; }; //

5.

AlgExpr , , . - isExpression , , . InfixExpr . - isExpression isBlank, - display 7 valueOf, 4.1. - isBlank , ? . 4.2. inExp endExpression, inExp InfixExpr main? . 4.3. , isExpression? , , main, . ; AlgExpr ; InfixExpr inExp;

6.

7.

8.

9.

getLength? isExpression? valueOf? , . , , . 6.1. F r o n t L i s t , BasicADT, 6.2. , Frontlist, Person, . Student, . Student GradStudent, . " " List, , , , , . (=) Stack ( 6) Queue ( 7) . : .

5.1. 5.2. 5.3. 5.4.

8. ++

405

1. " " L i s t , - removeAll - copyListNodes, L i s t , , (== ! =) (=). L i s t , BasicADT, SortedListj ; L i s t . L i s t , , position, . , , , remove.

2. 3. 4.

L i s t , - position, - , , . . , SortedList, locatePosition. 5. , . , , . , . L i s t . 6. 11 , . isEmpty, push, pop get Top , , t r a v e r s e . , . , , Stack, 6. 7. 8 7 , . , Queue, 7. 8. List, " ". 9. , 6. 9.1. . 9.2. . 10. , 7.10.1. .

406

II.

10.2. . . , List. . 12. , . SimpleString ( 5 6 4). ; . . . ' , 1. =, ==, !=, , =. 7 5 . , ; . , /* , / {*) (/) * . 6 6 . , SimpleString, isExpression, 5, valueOf^ 6. , 9. 13. 5 Queen, . , . 1 5 , . , , . 14. L i s t , , .

8. C++

407

9

... -

. . , . , . , , . , , , . , .

. , . , , , , , , - . , , . , ? 1 , . , , . , .. , , . , . . , , , . . , , . , , , . (analysis of algorithms) , . , '' '', "". , , , , , , . , , , . , , . , , . , . . , , . 9. 409

, ? C++ . . 1. ? , , Ai , 2. , , Ai, . , , , . , , . 2. ? . , . ? , Ai, , , . . 3. ? , . , , . , , . . , . , , , , . , , .

, . , 4 , retrieve - , items [-1]. , . , . .

410

II.

, . , , head, .^Node *cur = head; while(cur != NULL) cout item next; } // while (2"-1)*77, 0(2").

> 0{f(n)) , . , , . , log , 1. , , k * log 1 , . 9. 413

3*2

2 - 3 * + 10

. 9.2. > 2, 3 * , - 3 * + 10

, 1. , f{n) = log , = 1 . , , . 9.3. (. 9.3, ) , , . 0(1) < 0(log2/i) < 0() < Oin4og2n) < 0(1^) < (^) < 0(2") . ( . 9.3, . )

1 log2^

n*log2Ai

1 , , , (logarithmic algorithm) . , . , . , , . , . , . 6, ; (linear algorithm) . , , 0{n*log2n) , . .

I

fin)=l , . , z/=l .

414

II.

(quadratic algorithm) . . . (qubic algorithm) , . , , . 2" (exponential algorithm) , /(), g, , /, , , . . 0-. , 0(f(n)) " /()" " /(\ . 1. | . - , 0(^ + 4*71^ + 3*/), (^), , . 9.3, , , ^ , 4*/^ 3*/, , ^ + 4*/^ + 3* ^. , . , 0(^ + 4*^ + 3*/), , (^). , 0(/()), f{n) , . 9.3. 2. . , 0(5*/ ), , 0(/^). 0(/(7i)), /2 = 5. 3. 0(f(n))+0(g(n))=0(f(n)+g(n)). , , . , 0(^)+0(), , 0(^+), .1, 0(/^). . , . , , , . . . , , 9. 415

, . , , .. . (worts-case analysis) 0(/()), , , k*f(n) , . , , . , .)

10 1 3 10* 1092

100 1 6 102 664 10^ 10^1030

1.000

10,000

100.000

1,000,000

11092

1 9 1039,965

1 13 10^ 10^ 10810^2 103.010

1 16 10^ 10^10^0 10^5 .

1 19 10^ 10^10^2 10^8 10301,030

30 102 103 103

2 2

10^ 10910301

)100 ".

* 1092

75

50

25 4

1

|092

. 9.3. : ) ; )

416

II.

(average-case analysis) /. , 0(f{n))y k * f{n) , . , , . . . .

retrieve , , 0(1) . , ; . , r e t r i e v e i- /. 1 100- r e t r i e v e . , r e t r i e v e 0(1). retrieve r e t r i e v e , /- 0() . , 0(/). , , . retrieve? , . , r e t r i e v e . r e t r i e v e , . 25, r e t r i e v e . , , , , , . r e t r i e v e , , . , , . , . . , , 9. 417

. , , . , , . , , , . , 0(), 0(log2n). , 0(log2^) , ( < 25) . , , 0(), , k. . . 9.1. , , , . , , . , . . : " ." , , . , . , , . , , . , . . , . , , , . , , . , , , . , . , , .

418

II.

: . . . , 0(), , 0(), 0(1) , , , . . . , 0(1). . , . , 0(/). /2 . , ? , ? . . , ? , 2, , . , , , . , , . . , 1 , , . , .. . , = 2*, k . . 1. , . 2. , /2. 3. , /2^ .. , . , , , . , . k . , /2^=1. (, = 2^.) k , , k . = 2^, , k = log2Ai.

, ? , 2^' leftChildPtr , root->rightChildPtr . .

10.

473

. 10.14. , . 10.12,

. , , . - .// * * * * * * * * * * * * * * *

// TreeException.h // .// ****************

#include #include using namespace std; class TreeException : public exception { public: TreeException(const string & message ="") : exception(message.c_str0) { } }; // TreeException

//

II BinaryTree.h // .// ****************

#include "TreeException.h" #include "TreeNode.h" // TreeNode / / TreeltemType

474

II.

typedef void (*FunctionType)(TreeItemType& anitem); class BinaryTree ( public: // : BinaryTree(); BinaryTree(const TreeItemType& rootltem); BinaryTree(const TreeItemType& rootltem, BinaryTreeSc leftTree, BinaryTreeSc rightTree) ; BinaryTree(const BinaryTree& tree); virtual -BinaryTree 0 ;* " // : virtual bool isEmptyO const; virtual TreeltemType getRootData() const throw(TreeException); virtual void setRootData(const TreeItemType& newltem) throw(TreeException); virtual void attachLeft(const TreeltemTypeS: newltem) throw(TreeException); virtual void attachRight(const TreeItemType& newltem) throw(TreeException); virtual void attachLeftSubtree(BinaryTree& leftTree) throw(TreeException); virtual void attachRightSubtree(BinaryTree& rightTree) throw(TreeException); virtual void d