On that is linear search and it also works if the

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

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ng is completely O(n2). if (prev == 0) // there is no previous head = newnode; head newnode else prev->next = newnode; >next newnode newnode->next = curr; >next curr this also works if we're at the end How can we find a data item? As the data isn't in an array we can't use As Binary Search, so we're back to O(n) searches. O(n That is, linear search. And it also works if the list is empty! So we now have Insertion Sort with NO MOVES!!!! So NO Here's the code. Applied Programming The item we are looking for is searchdata. The searchdata nodePtr curr = head; while (curr != 0 && ListDataCmp(searchdata,curr->data) != 0) curr = curr->next; curr Either curr will equal the pointer to the node Either curr will containing the matching data, or it will reach the end of the list with curr being 0. We could also curr being have a flag to terminate the loop once the point where searchdata would be is passed. searchdata Applied Programming Deletion from an array was just as difficult as insertion. How is it with lists? It's as easy as insertion. 1. 1. Find where the item to delete is. Find 2. Unlink it from its predecessor, which has to be connected to the deleted node's successor. Applied Programming Step one is the same as it is for finding an item, Step but we again have to remember prev. but Applied Programming Here's our diagram from before. Head (prev) 1 nodePtr curr, prev; prev curr = head; prev = 0; while (curr != 0 && ListDataCmp(deldata,curr->data) != 0) { prev = curr; curr curr = curr->next; curr } Applied Programming (curr) 2 3 4 6 0 Let's delete the data item 2. Again, we finally get curr and prev. Again, curr and prev Applied Programming How do we want the pointers? The special case for removing the head (prev=0). Head (prev) Head (curr) (curr) 1 2 3 4 6 0 2 3 4 6 0 So That is, if (prev != 0) prev->next = curr->next; >next curr else head = curr->next; head curr prev->next = curr->next; >next curr and of course we would then delete curr; delete curr 1 Applied Programming Here's the current LinkedList ADT. Here's LinkedList #ifndef LINKLIST_H_ #define LINKLIST_H_ int ListDataCmp(const int&, const int&); &, int class LinkedList class Link...
View Full Document

This document was uploaded on 04/07/2014.

Ask a homework question - tutors are online