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.

114 Chap. 4 Lists, Stacks, <strong>and</strong> Queues/** Doubly linked list node */class DLink {priv<strong>at</strong>e E element;// Value for this nodepriv<strong>at</strong>e DLink next; // Pointer to next node in listpriv<strong>at</strong>e DLink prev; // Pointer to previous node}/** Constructors */DLink(E it, DLink p, DLink n){ element = it; prev = p; next = n; }DLink(DLink p, DLink n) { prev = p; next = n; }/** Get <strong>and</strong> set methods for the d<strong>at</strong>a members */DLink next() { return next; }DLink setNext(DLink nextval){ return next = nextval; }DLink prev() { return prev; }DLink setPrev(DLink prevval){ return prev = prevval; }E element() { return element; }E setElement(E it) { return element = it; }Figure 4.14 Doubly linked list node implement<strong>at</strong>ion with a freelist.of the header <strong>and</strong> tailer nodes mean th<strong>at</strong> there are no special cases to worry aboutwhen inserting into an empty list.The append method is also simple. Again, the Link class constructor sets theelement, prev, <strong>and</strong> next fields of the node when the new oper<strong>at</strong>or is executed.Method remove (illustr<strong>at</strong>ed by Figure 4.17) is straightforward, though thecode is somewh<strong>at</strong> longer. First, the variable it is assigned the value being removed.Note th<strong>at</strong> we must separ<strong>at</strong>e the element, which is returned to the caller,from the link object. The following lines then adjust the list.E it = curr.next().element(); // Remember valuecurr.next().next().setPrev(curr);curr.setNext(curr.next().next()); // Remove from listThe first line stores the value of the node being removed. The second line makesthe next node’s prev pointer point to the left of the node being removed. Finally,the next field of the node preceding the one being deleted is adjusted. The finalsteps of method remove are to upd<strong>at</strong>e the list length <strong>and</strong> return the value of thedeleted element.The only disadvantage of the doubly linked list as compared to the singly linkedlist is the additional space used. The doubly linked list requires two pointers pernode, <strong>and</strong> so in the implement<strong>at</strong>ion presented it requires twice as much overheadas the singly linked list.

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

Saved successfully!

Ooh no, something went wrong!