Document Sample

M ORE L INKING U P WITH L INKED L ISTS Chapter 11 1 2 C HAPTER C ONTENTS 11.1 Some Variants of Singly-Linked Lists 11.2 Linked Implementation of Sparse Polynomials 11.3 Doubly-Linked Lists and the Standard C++ list 11.4 Case Study: Larger-Integer Arithmetic 11.5 Other Multiply-Linked Lists 3 C HAPTER O BJECTIVES Survey common variants of linked lists and why they are used Study in detail an application of linked lists to implement sparse polynomials Describe doubly-linked lists and how they are used to implement C++ STL list container Build a class that makes it possible to do arithmetic with large integers Look briefly at some other applications of multiply-linked lists 4 L INKED L ISTS WITH H EAD N ODES Consider linked lists from Chapter 6 First node is different from others Has no predecessor Thus insertions and deletions must consider two cases First node or not first node The algorithm is different for each 5 L INKED L ISTS WITH H EAD N ODES Dual algorithms can be reduced to one Create a "dummy" head node Serves as predecessor holding actual first element Thus even an empty list has a head node, first->next==0 6 L INKED L ISTS WITH H EAD N ODES For insertion at beginning of list Head node is predecessor for new node newptr->next = predptr->next; predptr->next = newptr; 7 L INKED L ISTS WITH H EAD N ODES For deleting first element from a list with a head node Head node is the predecessor predptr->next = ptr->next; delete ptr; 8 C IRCULAR L INKED L ISTS Set the link in last node to point to first node Each node now has both predecessor and successor Insertions, deletions now easier Special consideration required for insertion to empty list, deletion from single item list 9 C IRCULAR L INKED L ISTS Traversal algorithm must be adjusted if (first != 0) // list not empty { ptr = first; do { // process ptr->data ptr = ptr->next; } while (ptr != first); } A do-while loop must be used instead of a while loop Why is this required? 10 P ROBLEM S OLUTION USING LINKED LIST Calculate (1+2*x^80) + (20+3*x^90) Solution? 11 L INKED I MPLEMENTATION OF S PARSE P OLYNOMIALS Consider a polynomial of degree n Can be represented by a list For a sparse polynomial this is not efficient 12 L INKED I MPLEMENTATION OF S PARSE P OLYNOMIALS We could represent a polynomial by a list of ordered pairs { (coef, exponent) … } Fixed capacity of array still problematic Wasted space for sparse polynomial 13 L INKED I MPLEMENTATION OF S PARSE P OLYNOMIALS Linked list of these ordered pairs provides an appropriate solution Each node has form shown Now whether sparse or well populated, the polynomial is represented efficiently 14 L INKED I MPLEMENTATION OF S PARSE P OLYNOMIALS Note start of Polynomial class template Type parameter CoefType Term and Node are inner classes Addition operator Adds coefficients of like degrees Must traverse the two addend polynomials Requires temporary pointers for each polynomial (the addends and the resulting sum) 15 A DDITION O PERATOR Requires temporary pointers for each polynomial (the addends and the resulting sum) 16 A DDITION O PERATOR As traversal takes place Compare exponents If different, node with smaller exponent and its coefficient attached to result polynomial If exponents same, coefficients added, new corresponding node attached to result polynomial 17 D OUBLY -L INKED L ISTS Bidirectional lists Nodes have data part, forward and backward link Facilitates both forward and backward traversal Requires pointers to both first and last nodes 18 D OUBLY -L INKED L ISTS To insert a new node Set forward and backward links to point to predecessor and successor Then reset forward link of predecessor, backward link of successor 19 D OUBLY -L INKED L ISTS To delete a node Reset forward link of predecessor, backward link of successor Then delete removed node T HE STL LIST <T> C LASS 20 T EMPLATE A sequential container Optimized for insertion and erasure at arbitrary points in the sequence. Implemented as a circular doubly-linked list with head node. 21 C OMPARING L IST < T > W ITH O THER C ONTAINERS Property Array vector<T> deque<T> list<T> Direct/random access ([]) + (exclnt) + (good) X Sequential access + + + Insert/delete at front -(poor) - + + Insert/delete at end + + + + Insert/delete in middle - - - + Overhead lowest low low/medium high Note : list<T> does not support direct access does not have the subscript operator [ ]. 22 N EED HELP ??? Free workshops that are available to SJSU students. http://www.sjsu.edu/larc/Services_for_Students/Get _Tutoring/courses_tutored/ http://www.sjsu.edu/counseling/ http://www.drc.sjsu.edu/Services/retentions/answer s/StudySkillsTimemangement/answerStudySkillsTime mangement.aspx http://www.sjsu.edu/writingcenter/ 23 LIST < T > I TERATORS list<T>'s iterator is "weaker" than that for vector<T>. vector<T>: random access iterators list<T>: bidirectional iterators Operations in common ++ Move iterator to next element (like ptr = ptr-> next) -- Move iterator to preceding element (like ptr = ptr-> prev) * dereferencing operator (like ptr-> data) 24 LIST < T > I TERATORS Operators in common = assignment (for same type iterators) it1 = it2 makes it1 positioned at same element as it2 == and != (for same type iterators) checks whether iterators are positioned at the same element See basic list operations, Table 11-2, pg 621 View demonstration of list operations, Fig. 11-1 25 B ASIC L IST O PERATIONS ( REFER TABLE 11.2) list <T> alist; list <T> alist(n); list <T> alist(n, value); list <T> alist(firstprt, lastptr); alist.empty(); alist.size(); alist.insert(pos, value); alist.insert(pos,n,value); 26 B ASIC L IST O PERATIONS ( REFER TABLE 11.2) alist.pop_back(); alist.pop_front(); alist.push_back(value); alist.push_front(value); alist.erase(pos); alist.erase(pos1, pos2);// pos1, pos2 are iterators alist.remove(value); 27 B ASIC L IST O PERATIONS ( REFER TABLE 11.2) alist.begin();//for iterators alist.end();//for iterators alist.sort(); alist.reverse(); alist1.swap(alist2); alist1=alist2; alist1==alist2; T HE STL LIST <T> C LASS 28 T EMPLATE Node structure struct list_node { pointer next, prev; T data; } T HE STL LIST <T> C LASS 29 T EMPLATE But it's allo/deallo-cation scheme is complex Does not simply using new and delete operations. Using the heap manager is inefficient for large numbers of allo/deallo-cations Thus it does it's own memory management. 30 T HE STL LIST <T> M EMORY M ANAGEMENT When a node is allocated 1. If there is a node on the free list, allocate it. • This is maintained as a linked stack 2. If the free list is empty: a) Call the heap manager to allocate a block of memory (a "buffer", typically 4K) b) Carve it up into pieces of size required for a node of a list<T>. T HE STL LIST <T> M EMORY 31 M ANAGEMENT When a node is deallocated Push it onto the free list. When all lists of this type T have been destroyed Return it to the heap 32 C ASE S TUDY: L ARGE -I NTEGER A RITHMETIC Recall that numeric representation of numbers in computer memory places limits on their size 32 bit integers, two's complement max 2147483647 We will design a BigInt class Process integers of any size For simplicity, nonnegative integers only 33 B IG I NT D ESIGN First step : select a storage structure We choose a linked list Each node stores a block of up to 3 consecutive digits Doubly linked list for traversing in both directions 34 B IG I NT D ESIGN Use blocks of length 3, separated by spaces As each new block entered, node added at end Output is traversal, left to right 35 B IG I NT D ESIGN Addition adds the groupings right to left Keeping track of carry digits 36 B IG I NT I MPLEMENTATION Standard list type provides all the tools we need Note class declaration, Fig. 11.3A View class definition, Fig. 11.3B Driver program to demonstrate use of the class, Fig 11.4 37 M ULTIPLY -O RDERED L ISTS Ordered linked list Nodes arranged so data items are in ascending/descending order Straightforward when based on one data field However, sometimes necessary to maintain links with a different ordering, more than 2. Possible solution Separate ordered linked lists – but wastes space 38 M ULTIPLY -O RDERED L ISTS Better approach Single list Multiple links 39 S PARSE M ATRICES Usual storage is 2D array or 2D vector If only a few nonzero entries Can waste space Stored more efficiently with linked structure Similar to sparse polynomials Each row is a linked list Store only nonzero entries for the row 40 S PARSE M ATRICES For A = we represent with 41 S PARSE M ATRICES This still may waste space Consider if many rows were all zeros Alternative implementation Single linked list Each node has row, column, entry, link Resulting list 42 S PARSE M ATRICES However … this loses direct access to rows Could replace array of pointers with Linked list of row head nodes Each contains pointer to non empty row list 43 S PARSE M ATRICES If columnwise processing is desired Use orthogonal list Each node stores row, column, value, pointer to row successor, pointer to column successor 44 S PARSE M ATRICES Note the resulting representation of the matrix A= 45 G ENERALIZED L ISTS Examples so far have had atomic elements The nodes are not themselves lists Consider a linked list of strings The strings themselves can be linked lists of characters This is an example of a generalized list NYHOFF, ADTS, DATA STRUCTURES AND PROBLEM SOLVING WITH C++, SECOND EDITION, © 2005 PEARSON EDUCATION, INC. ALL RIGHTS RESERVED. 0-13-140909-3 46 G ENERALIZED L ISTS Commonly represented as linked lists where Nodes have a tag field along with data and link Tag used to indicate whether data field holds Atom Pointer to a list 47 G ENERALIZED L ISTS Lists can be shared To represent (2, (4,6), (4,6)) For polynomials in two variables P(x,y) = 3 + 7x + 14y2 + 25y7 – 9x2y7 + 18x6y7

DOCUMENT INFO

Shared By:

Categories:

Tags:

Stats:

views: | 22 |

posted: | 2/10/2011 |

language: | English |

pages: | 47 |

OTHER DOCS BY parikhparth23

How are you planning on using Docstoc?
BUSINESS
PERSONAL

By registering with docstoc.com you agree to our
privacy policy and
terms of service, and to receive content and offer notifications.

Docstoc is the premier online destination to start and grow small businesses. It hosts the best quality and widest selection of professional documents (over 20 million) and resources including expert videos, articles and productivity tools to make every small business better.

Search or Browse for any specific document or resource you need for your business. Or explore our curated resources for Starting a Business, Growing a Business or for Professional Development.

Feel free to Contact Us with any questions you might have.