8a - Collections

# 0 listdatacmpnewdatacurr data 0

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ult; } Applied Programming int ListDataCmp(const Video& v1, const Video& v2) { int result = strcmp(v1.Title, v2.Title); if (result == 0) { if (v1.Year > v2.Year) result = -1; result else if (v1.Year < v2.Year) result = 1; } return result; } Applied Programming In C++ this would be nodePtr curr; curr = head; while (curr!= 0 && != ListDataCmp(newdata,curr->data) >= 0) ListDataCmp(newdata,curr curr = curr->next; curr if (curr != 0) // goes before curr // curr else // goes at the end Unfortunately, we need to be able to link the new Unfortunately, node to the one before curr, so we have to curr so remember the previous node. remember Applied Programming Applied Programming nodePtr curr, prev; prev Here's our diagram of the list so far. curr = head; prev = 0; while (curr != 0 && ListDataCmp(newdata,curr->data) >= 0) { prev = curr; curr curr = curr->next; curr } // // // // // // // // new node goes if prev is 0, prev is so we have to if curr is 0, curr after prev and prev and it goes on the change head as it is going on Head 1 2 3 6 0 4 Let's see how we go about adding a new Let's data item. data before curr curr head of list well the end Suppose we want to add 5. Applied Programming Applied Programming We firstly create a new node for the list. We now find where it goes. Head Head 1 2 3 6 0 4 (prev) 1 2 4 3 (curr) 6 0 (newnode) Let's put it here in our diagram. 5 We will ultimately get values for curr and prev. and prev W e don't need to put a value in next. We next All these are pointers, of course. Applied Programming Note that prev->next iis equal to curr. s Note prev curr Head 2 3 Applied Programming If we were adding to the head of the list prev is 0. If prev (prev) 1 5 (curr) 4 Head (curr) 6 0 (newnode) 5 So we want the pointers to finally look like this. Applied Programming 1 2 3 4 6 0 (newnode) 0 So prev->next = newnode; >next newnode newnode->next = curr; >next curr head = newnode; head newnode Applied Programming So the final code fragment is // So now sorti...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online