12.07.2015 Views

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Sec. 4.1 Lists 115// Singly linked list node with freelist supportclass Link {private E element; // Value for this nodeprivate Link next; // Point <strong>to</strong> next node in list// Construc<strong>to</strong>rsLink(E it, Link nextval){ element = it; next = nextval; }Link(Link nextval) { next = nextval; }Link next() { return next; }Link setNext(Link nextval){ return next = nextval; }E element() { return element; }E setElement(E it) { return element = it; }// Extensions <strong>to</strong> support freelistsstatic Link freelist = null; // Freelist for the class// Get new linkstatic Link get(E it, Link nextval) {if (freelist == null)return new Link(it, nextval); // Get from "new"Link temp = freelist;// Get from freelistfreelist = freelist.next();temp.setElement(it);temp.setNext(nextval);return temp;}void release() {element = null;next = freelist;freelist = this;}} // class Link// Return Link <strong>to</strong> freelist// Drop reference <strong>to</strong> the elementFigure 4.11 Implementation for the Link class with a freelist. The staticdeclaration for member freelist means that all Link class objects share thesame freelist pointer variable instead of each object s<strong>to</strong>ring its own copy.In the implementation shown here, the link class is augmented with methodsget <strong>and</strong> release. Figure 4.11 shows the reimplementation for the Link class <strong>to</strong>support these methods. Note how simple they are, because they need only remove<strong>and</strong> add an element <strong>to</strong> the front of the freelist, respectively.The freelist methods get <strong>and</strong> release both run in Θ(1) time, except in thecase where the freelist is exhausted <strong>and</strong> the new operation must be called.

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

Saved successfully!

Ooh no, something went wrong!