# h3-sol - Homework 3 Solutions Fundamental Algorithms Spring...

This preview shows pages 1–3. Sign up to view the full content.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
SOLUTION: (a) We implement the dictionary ADT with linked lists as follows. First we describe how a linked list L represents a dictionary. The linked list L has a node called the head , and it is denoted by L. head . Every node u in the list has two fields, u. key and u. data . Thus ( u. key , u. data ) represents an item stored in L . Also, u has a pointer u. next to the next node (unless u is the last node in which case u. next = nil ). From the node L. head , we can reach every node in the list using the next pointer. For simplicity, we assume there is a field called L. tail that gives us the last node in the list. We use “shell programming” based on the following list traversal algorithm: ListTraversal ( L ): u L. head while ( u negationslash = nil ) VISIT( u ) u u. next CLEANUP() The macros VISIT and CLEANUP can be empty initially. To implement the various other operations, we can redefine VISIT and CLEANUP appropriately. We now implement the 3 dictionary operations: (a) lookUp ( K ): We use the ListTraversal shell, but define VISIT( u ) as the fol- lowing macro: V ISIT ( u ) : if ( u. key = K ) return ( u ) Thus, if the key K is found in u , we exit from the while-loop and return u . The CLEANUP() macro is: CLEANUP() : return ( nil ) (b) insert ( K, D ): We use the ListTraversal shell, but define VISIT( u ) as the following macro: V ISIT ( u ) : if ( u. key = K ) return ( nil ) Thus, if the key K is found in u , we return nil , indicating failure (duplicate key).
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### What students are saying

• As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

Kiran Temple University Fox School of Business ‘17, Course Hero Intern

• I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

Dana University of Pennsylvania ‘17, Course Hero Intern

• The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

Jill Tulane University ‘16, Course Hero Intern