Lecture 10

9 10 dont forget the two initializations before this

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: will crash! 9 10 Don’t forget the two initializations before this loop: Solution: Check specifically for NULL. while ((cur != NULL) && ( X > cur data)) { prev = cur; cur = cur next; } prev = NULL; cur = head; Now we know where to insert: At the place that prev points to. 11 12 Next Step: Create the actual Node. That’s easy: Third step: Thread in the new node. 1) We need a pointer from node [41] to the node [50]. We need one more pointer “newitem”. 2) We need a pointer from [50] to [66]. newitem = new node; newitem data = X; 13 head 14 What points to [66] right now? cur !!! 12 30 41 66 newitem next = cur; prev What points to [50] right now? newitem !!! newitem 50 cur prev next = newitem; 15 if (prev != NULL) { newitem next = cur; prev next = newitem; } else { newitem next = head; head = newitem; } Are we done? No. If we want to insert at the beginning of the list, prev = NULL. prev 16 next = newitem; // will CRASH! Do we have problems at the end also? NO! Note that we don’ use cur ! !! t 17 18 head 12 30 41 prev What if the list is empty to begin with? head must be initialized before it can be used. cur if (head = =NULL) { head = new node; head data = X; head next = NULL; } newitem 3 19 Are we done? Almost. What if the number we want to insert is already in the list? It’s our choice. We can permit that or prohibit it. Let’ prohibit it. s if((cur = = NULL) || (X != cur // not a duplicate else // it’ a duplicate s data)) 21 20...
View Full Document

This document was uploaded on 03/31/2014 for the course CS 114 at NJIT.

Ask a homework question - tutors are online