1 / 48

Linked Lists

Linked Lists. Chapter 4. Why “linked lists”. Insert “FAT” ? Or delete something. Usual way to draw a linked list. Inserting into a linked list. Delete GAT. Defining a node in C++. class ThreeLetterNode { private: char data[3]; ThreeLetterNode * link; }.

vidor
Télécharger la présentation

Linked Lists

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Linked Lists Chapter 4

  2. Why “linked lists” Insert “FAT” ? Or delete something

  3. Usual way to draw a linked list

  4. Inserting into a linked list

  5. Delete GAT

  6. Defining a node in C++ • class ThreeLetterNode { private: char data[3]; ThreeLetterNode* link; }

  7. Example 4.1: The class definitions

  8. Designing a chain class in C++: Design attempt 1 • Use a global variable first which is a pointer of ThreeLetterNode. • Unable to access to private data members: data and link. • ThreeLetterNode *first; firstdata, firstlink firstdata[0], firstdata[1], firstdata[2]

  9. Designing a chain class in C++: Design attempt 2 • Make data members public or define public member functions GetLink(), SetLink() and GetData() • Defeat the purpose of data encapsulation • The ideal solution would only permit those functions that perform list manipulation operations (like inserting a node into or deleting a node from a chain) access to the data members of ThreeLetterNode

  10. Designing a chain class in C++: Design attempt 3 • Use of two classes. • Create a class that represents the linked list. • The class contains the items of another objects of another class. • HAS-A • A data object of type A HAS-A data object of type B if A conceptually contains B or B is a part of A. • Eg. Computer HAS-A Processor, Book HAS-A Page

  11. Conceptual relationship between ThreeLetterChain and ThreeLetterNode Actual relationship between ThreeLetterChain and ThreeLetterNode

  12. Program 4.1: Composite classes

  13. Program 4.2: Nested classes

  14. Pointer manipulation in C++ • Two pointer variables of the same type can be compared. • Eg. x == y, x != y, x == 0 x = y *x = *y

  15. Program 4.3: Creating a two-node list

  16. Program 4.4: Inserting a node

  17. Program 4.5: Deleting a node Example: Delete the second node Delete the first node Reference: J.L. Huang@NCTU

  18. Program 4.6: Template definition of chains

  19. Iterator • An iterator is an object that is used to access the elements of a container class one by one

  20. Program 4.11: Inserting at the back of a list

  21. Program 4.12: Concatenating two chains

  22. Program 4.13: Reversing a list template <class T> void Chain<T>::Reverse() {// A chain is reversed so that (a1, …, an)becomes(an, …, a1) ChainNode<T> *current = first, *previous = 0; // previoustrails current while (current) { ChainNode<T> *r = previous; previous = current; // rtrailsprevious current = current  link; // currentmoves to next node previouslink = r; // link previousto preceding node } first = previous; }

  23. Circular lists How to insert at the front of a circular list? Read Program 4.14

  24. Linked stacks and queues Read Program 4.19, 4.20, 4.21 and 4.22

  25. Program 4.23: Polynomial class definition structTerm { intcoef; intexp; Term Set(intc,inte) {coef = c;exp = e;return *this;}; }; classPolynomial { public: // public functions defined here private: Chain<Term> poly; };

  26. Polynomial representation (a) 3x14+2x8+1 (b) 8x14-3x10+10x6

  27. Adding polynomials: 3x14+2x8+1 and 8x14-3x10+10x6

  28. Equivalence classes • For an arbitrary relation by the symbol  • Reflexive • xx • Symmetric • If xy, then yx • Transitive • If xyand yz, then xz • A relation over a set, S, is said to be an equivalence relation over S if and only if it is symmetric, reflexive, and transitive over S.

  29. Example • 04, 31, 610, 89, 74, 68, 35, 211, 110 • Three equivalent classes: {0,2,4,7,11}; {1,3,5}; {6,8,9,10}

  30. Program 4.26: First version of equivalence algorithm void Equivalence() { initialize; while more pairs { input the next pair (i,j); process this pair; } initialize for output; for(each object not yet output) output the equivalence class that contains his object; }

  31. Program 4.27: A more detail version of equivalence algorithm voidEquivalence() { readn; initializefirst[0:n-1] to0and out[0:n-1] tofalse; whilemore pairs { read the next pair(i, j); put jon the chainfirst[i]; put i on the chainfirst[j]; } for (i = 0;i < n;i++) if (!out[i]) { out[i] = true; output the equivalence class that contains objecti; } }

  32. Lists after pairs have been input 04, 31, 610, 89, 74, 68, 35, 211, 110

  33. Program 4.28: C++ function to find equivalence classes classENode{ friendvoidEquivalence( ); public: ENode(intd = 0) {data = d; link = 0;} private: intdata; ENode *link; };

  34. voidEquivalence( ) {// input and output ifstreaminFile( "equiv.in", ios::in); if (!inFile) throw “Cannot open input file.”; inti, j, n; inFile >> n; // read number of objects // initializefirstandout ENode **first = newENode* [n]; bool *out = newbool[n]; // use STL functionfillto initialize fill (first, first + n, 0); fill (out, out + n, false);

  35. // Phase 1: input equivalence pairs inFile >>i >> j; while (inFile.good()) { //check end of file first[i] = newENode(j, first[i]) first[j] = newENode(i, first[j]) inFile >>i >> j; }

  36. // Phase 2: output equivalence classes for (i= 0;i < n;i++) if (!out[i]) { // needs to be output cout << endl << "A new class: " << i; out[i] = true; ENode *x = first[i];ENode *top = 0; // initialize stack while (1) {//find rest of class while (x) { // process the list j = xdata; if (!out[j]) { cout << ", " << j; out[j] = true; ENode *y = xlink; xlink = top; top = x; x = y; } elsex = xlink; } if (!top) break; x = first [topdata]; top = toplink; // unstack } // end of while(1)

  37. } for (i = 0; i < n;i++) while (first[i]) { ENode *delnode = first[i]; first[i] = delnodelink; deletedelnode; } delete [] first;delete [] out; }

  38. Sparse matrices 1 0 4 Next nonzero column Next nonzero row

  39. Example Thus for an nxmsparse matrix with r nonzero terms, the number of nodes needed is max{n, m} + r + 1.

  40. Program 4.29: Class definition for sparse matrices structTriple{introw, col, value;}; classMatrix; classMatrixNode{ friendclassMatrix; friendistream&operator>>(istream&, Matrix&); private: MatrixNode *down , *right; boolhead; union { MatrixNode *next; Tripletriple; }; MatrixNode(bool, Triple*); // constructor }

  41. MatrixNode::MatrixNode(boolb, Triple *t) // constructor { head = b; if (b) {right = down = this;} // row/column header node elsetriple = *t; // element node or header node for list of header nodes } classMatrix{ friendistream&operator>>(istream&, Matrix&); public: ~Matrix(); // destructor private: MatrixNode *headnode; };

  42. Doubly linked lists • Move in forward and backward direction. • How to get the preceding node during deletion or insertion? • Using 2 pointers • Node in doubly linked list • left link field (left link) • data field (item) • right link field (right link)

  43. Doubly linked circular list with header node Empty doubly linked circular list with header node

  44. Program 4.32: Class definition of a doubly linked list class DblList; class DblListNode { friend class DblList; private: intdata; DblListNode*left,*right; }; class DblList { public: // List manipulation operations . . private: DblListNode*first; // points to header node };

  45. Program 4.33: Deletion from a doubly linked circular list void DblList :: Delete(DblListNode *x) { if (x = = first) throw "Deletion of header node not permited"; else { x→left→right = x→right; //(1) x→right→left = x→left; //(2) delete x; } Reference: J.L. Huang@NCTU

  46. Program 4.34: Insertion into a doubly linked circular list void DblList:: Insert(DblListNode *p, DblListNode *x) { // insert node pto the right of nodex p→left = x; //(1) p→right = x→right; //(2) x→right→left = p; //(3) x→right= p; //(4) } Reference: J.L. Huang@NCTU

More Related