11.07.2015 Views

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

110 Chap. 4 Lists, Stacks, <strong>and</strong> Queues/** Insert "it" <strong>at</strong> current position */public void insert(E it) {curr.setNext(Link.get(it, curr.next())); // Get linkif (tail == curr) tail = curr.next(); // New tailcnt++;}/** Append "it" to list */public void append(E it) {tail = tail.setNext(Link.get(it, null));cnt++;}/** Remove <strong>and</strong> return current element */public E remove() {if (curr.next() == null) return null; // Nothing to removeE it = curr.next().element();// Remember valueif (tail == curr.next()) tail = curr; // Removed lastLink tempptr = curr.next(); // Remember linkcurr.setNext(curr.next().next()); // Remove from listtempptr.release();// Release linkcnt--;// Decrement countreturn it;// Return removed}Figure 4.12 Linked-list class members th<strong>at</strong> are modified to use the freelist versionof the link class in Figure 4.11.DE, regardless of the number of elements actually stored in the list <strong>at</strong> any giventime. The amount of space required for the linked list is n(P + E). The smallerof these expressions for a given value n determines the more space-efficient implement<strong>at</strong>ionfor n elements. In general, the linked implement<strong>at</strong>ion requires less spacethan the array-based implement<strong>at</strong>ion when rel<strong>at</strong>ively few elements are in the list.Conversely, the array-based implement<strong>at</strong>ion becomes more space efficient whenthe array is close to full. Using the equ<strong>at</strong>ion, we can solve for n to determinethe break-even point beyond which the array-based implement<strong>at</strong>ion is more spaceefficient in any particular situ<strong>at</strong>ion. This occurs whenn > DE/(P + E).If P = E, then the break-even point is <strong>at</strong> D/2. This would happen if the elementfield is either a four-byte int value or a pointer, <strong>and</strong> the next field is a typical fourbytepointer. Th<strong>at</strong> is, the array-based implement<strong>at</strong>ion would be more efficient (ifthe link field <strong>and</strong> the element field are the same size) whenever the array is morethan half full.As a rule of thumb, linked lists are more space efficient when implementinglists whose number of elements varies widely or is unknown. Array-based lists aregenerally more space efficient when the user knows in advance approxim<strong>at</strong>ely howlarge the list will become.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!