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.

Sec. 4.1 Lists 115/** Insert "it" <strong>at</strong> current position */public void insert(E it) {curr.setNext(new DLink(it, curr, curr.next()));curr.next().next().setPrev(curr.next());cnt++;}/** Append "it" to list */public void append(E it) {tail.setPrev(new DLink(it, tail.prev(), tail));tail.prev().prev().setNext(tail.prev());cnt++;}/** Remove <strong>and</strong> return current element */public E remove() {if (curr.next() == tail) return null; // Nothing to removeE it = curr.next().element(); // Remember valuecurr.next().next().setPrev(curr);curr.setNext(curr.next().next()); // Remove from listcnt--;// Decrement the countreturn it;// Return value removed}/** Move curr one step left; no change if <strong>at</strong> front */public void prev() {if (curr != head) // Can’t back up from list headcurr = curr.prev();}Figure 4.15 Implement<strong>at</strong>ions for doubly linked list insert, append,remove, <strong>and</strong> prev methods.Example 4.1 There is a space-saving technique th<strong>at</strong> can be employed toelimin<strong>at</strong>e the additional space requirement, though it will complic<strong>at</strong>e theimplement<strong>at</strong>ion <strong>and</strong> be somewh<strong>at</strong> slower. Thus, this is an example of aspace/time tradeoff. It is based on observing th<strong>at</strong>, if we store the sum oftwo values, then we can get either value back by subtracting the other. Th<strong>at</strong>is, if we store a + b in variable c, then b = c − a <strong>and</strong> a = c − b. Of course,to recover one of the values out of the stored summ<strong>at</strong>ion, the other valuemust be supplied. A pointer to the first node in the list, along with the valueof one of its two link fields, will allow access to all of the remaining nodesof the list in order. This is because the pointer to the node must be the sameas the value of the following node’s prev pointer, as well as the previousnode’s next pointer. It is possible to move down the list breaking apartthe summed link fields as though you were opening a zipper. Details forimplementing this vari<strong>at</strong>ion are left as an exercise.

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

Saved successfully!

Ooh no, something went wrong!