{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Tutorial_9_Sol-for-viewing-printing

# Tutorial_9_Sol-for-viewing-printing - (Note other correct...

This preview shows pages 1–2. Sign up to view the full content.

CC2203 Data Structures and Algorithms Sem 2, 2009-2010 Tutorial 9 Solution Exercise 1 answer (a) public Object getRearElement() { Node p; if (isEmpty()) return null; // return null if the queue is empty else { p = front; while (p.next != null) p = p.next; return p.element; // return the element at the queue rear } } (Note: other correct algorithm is acceptable.) (b) public Object remove() { if (isEmpty()) return null; // return null if the queue is empty Object frontElement = front.element; front = front.next; // remove an element from the queue front return frontElement; // return removed element } (Note: other correct algorithm is acceptable.) (c) public boolean empty(LinkedQueue q) { // return true iff stack is empty return q.isEmpty(); } (Note: other correct algorithm is acceptable.) (d) public Object peek(LinkedQueue q) { // return top element of stack without removing it if (empty(q)) System.out.println("Empty Stack! Do not peek."); return q.getRearElement();

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: } (Note: other correct algorithm is acceptable.) CC2203 Data Structures and Algorithms Sem 2, 2009-2010 (e) public void push(LinkedQueue q, Object theElement) { // add theElement to the top of the stack q.put(theElement); } (Note: other correct algorithm is acceptable.) (f) public Object pop(LinkedQueue q) { // remove top element of stack and return it if (empty(q)) { System.out.println("Empty Stack! Do not pop."); return null; } else { LinkedQueue temp_q = new LinkedQueue(); Object x; x = q.remove(); while (!q.isEmpty()) { temp_q.put(x); x = q.remove(); } while (!temp_q.isEmpty()) q.put(temp_q.remove()); return x; } } (Note: other correct algorithm is acceptable.) (g) Front=21, Rear=78, Removed element=21 Front=43, Rear=78, Removed element=43 Front=78, Rear=78, Removed element=78 Empty Stack! Do not peek. Empty Stack! Do not pop. Top element=74, Popped element=74 Top element=102, Popped element=102 Top element=29, Popped element=29...
View Full Document

{[ snackBarMessage ]}

### Page1 / 2

Tutorial_9_Sol-for-viewing-printing - (Note other correct...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online