{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

# lists - Examples and Exercises on Linked Lists 1...

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

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

View Full Document
Exercise Q: Write the code with the smallest number of assignments (=) which will build the above memory structure. It requires 3 calls to malloc(). 3 int assignments (=) to setup the ints. 4 pointer assignments to setup head and the 3 next fields. With a little cleverness and knowledge of the C language, this can all be done with 7 assignment operations (=). 2. Length() Function The Length() function takes a linked list and computes the number of elements in the list. Length() is a simple list function. /* Given a linked list head pointer, compute and return the number of nodes in the list. */ int Length(struct node* head) { struct node* current = head; int count = 0; while (current != NULL) { count++; current = current->next; } return count; } Exercise void LengthTest() { struct node* myList = BuildOneTwoThree(); int len = Length(myList); // results in len == 3 }
What if we said head = NULL; at the end of Length() — would that mess up the myList variable in the caller? Ans: No. head is a local which was initialized with a copy of the actual parameter, but changes do not automatically trace back to the actual parameter. Changes to the local variables in one function do not affect the locals of another function.

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

View Full Document
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