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

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

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

120 Chap. 4 Lists, Stacks, <strong>and</strong> Queues/** Linked stack implement<strong>at</strong>ion */class LStack implements Stack {priv<strong>at</strong>e Link top;// Pointer to first elementpriv<strong>at</strong>e int size;// Number of elements/** Constructors */public LStack() { top = null; size = 0; }public LStack(int size) { top = null; size = 0; }/** Reinitialize stack */public void clear() { top = null; size = 0; }/** Put "it" on stack */public void push(E it) {top = new Link(it, top);size++;}/** Remove "it" from stack */public E pop() {assert top != null : "Stack is empty";E it = top.element();top = top.next();size--;return it;}/** @return Top value */public E topValue() {assert top != null : "Stack is empty";return top.element();}/** @return Stack length */public int length() { return size; }4.2.2 Linked StacksFigure 4.20 Linked stack class implement<strong>at</strong>ion.The linked stack implement<strong>at</strong>ion is quite simple. The freelist of Section 4.1.2 isan example of a linked stack. Elements are inserted <strong>and</strong> removed only from thehead of the list. A header node is not used because no special-case code is requiredfor lists of zero or one elements. Figure 4.20 shows the complete linked stackimplement<strong>at</strong>ion. The only d<strong>at</strong>a member is top, a pointer to the first (top) link nodeof the stack. Method push first modifies the next field of the newly cre<strong>at</strong>ed linknode to point to the top of the stack <strong>and</strong> then sets top to point to the new linknode. Method pop is also quite simple. Variable temp stores the top nodes’ value,while ltemp links to the top node as it is removed from the stack. The stack isupd<strong>at</strong>ed by setting top to point to the next link in the stack. The old top node isthen returned to free store (or the freelist), <strong>and</strong> the element value is returned.

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

Saved successfully!

Ooh no, something went wrong!