Solutions to a few of the review problems:

Similar documents
Abstract Data Types - Lists Arrays implementa4on Linked- lists implementa4on

1/18/12. Chapter 5: Stacks, Queues and Deques. Stacks. Outline and Reading. Nancy Amato Parasol Lab, Dept. CSE, Texas A&M University

DNHI Homework 3 Solutions List, Stacs and Queues

Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue

CE204 Data Structures and Algorithms Part 2

DataStruct 5. Stacks, Queues, and Deques

Assignment 1. Check your mailbox on Thursday! Grade and feedback published by tomorrow.

Stacks (5.1) Abstract Data Types (ADTs) CSE 2011 Winter 2011

CH ALGORITHM ANALYSIS CH6. STACKS, QUEUES, AND DEQUES

CSE 143 SAMPLE MIDTERM

Queues COL 106. Slides by Amit Kumar, Shweta Agrawal

Basic Data Structures

CS171 Midterm Exam. October 29, Name:

Stack ADT. ! push(x) puts the element x on top of the stack! pop removes the topmost element from the stack.

Discussion 2C Notes (Week 3, January 21) TA: Brian Choi Section Webpage:

Basic Data Structures 1 / 24

CSE 131 Computer Science 1 Module 9a: ADT Representations. Stack and queue ADTs array implementations Buffer ADT and circular lists

Agenda. Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList

1.00 Lecture 26. Data Structures: Introduction Stacks. Reading for next time: Big Java: Data Structures

Big- (O): c.) binary search O(logn)

Lecture 3 Linear Data Structures: Arrays, Array Lists, Stacks, Queues and Linked Lists

CS231 - Spring 2017 Linked Lists. ArrayList is an implementation of List based on arrays. LinkedList is an implementation of List based on nodes.

Computer Science 210: Data Structures. Linked lists

Data structure is an organization of information, usually in memory, for better algorithm efficiency.

The Java Collections Framework. Chapters 7.5

Abstract Data Types - Lists Arrays implementation Linked-lists implementation

COMP 103. Data Structures and Algorithms

Lists. ordered lists unordered lists indexed lists 9-3

ECE Fall st Midterm Examination (120 Minutes, closed book)

Data Structures and Algorithms Notes

Lecture 4. The Java Collections Framework

Lecture 3 Linear Data Structures

An Introduction to Data Structures

C Sc 227 Practice Test 2 Section Leader Your Name 100pts. a. 1D array b. PriorityList<E> c. ArrayPriorityList<E>

Programming II (CS300)

Iterators and Sequences

1.00 Introduction to Computers and Engineering Problem Solving. Final Examination - May 19, 2004

CSE 143 SAMPLE MIDTERM SOLUTION

Lists. CSC212 Lecture 8 D. Thiebaut, Fall 2014

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 2/10/2013

Computer Science 210 Data Structures Siena College Fall Topic Notes: Linear Structures

Data Structure: Lists and Iterators. Instructor: Prof. Young-guk Ha Dept. of Computer Science & Engineering

Notes on access restrictions

Generics. IRS W-9 Form

Programming II (CS300)

CPSC 221: Algorithms and Data Structures Lecture #1: Stacks and Queues

Data Abstraction and Specification of ADTs

Advanced Java Concepts Unit 3: Stacks and Queues

CS 455 Midterm 2 Spring 2018 [Bono] Apr. 3, 2018

Linear Data Structures

Linear Structures. Linear Structure. Implementations. Array details. List details. Operations 4/18/2013

CMP Points Total Midterm Spring Version (16 Points) Multiple Choice:

Announcements. Prelude (2) Prelude (1) Data Structures and Information Systems Part 1: Data Structures. Lecture 6: Lists.

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

Introduction to Computer Science II (CSI 1101) Final Examination

CPSC 221: Algorithms and Data Structures ADTs, Stacks, and Queues

EXAMINATIONS 2012 Trimester 1, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

Lecture 3 Linear Data Structures

Agenda. Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList!

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

ITI Introduction to Computing II

ADVANCED DATA STRUCTURES USING C++ ( MT-CSE-110 )

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

1 P age DS & OOPS / UNIT II

COMP 250 Winter generic types, doubly linked lists Jan. 28, 2016

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

Computer Science 1 Ah

Implementing Lists, Stacks, Queues, and Priority Queues

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss

Input-Output and Exception Handling

CS61B Spring 2016 Guerrilla Section 2 Worksheet

Stacks, Queues (cont d)

Lecture 3 Linear Data Structures

Chapter 13: Collections Lab Exercises

Lists using LinkedList

Linked Structures Chapter 13. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Data Structures Brett Bernstein

Homework 2: Imperative Due: 5:00 PM, Feb 15, 2019

Your Topic Goes Here Queue

COMP250: Stacks. Jérôme Waldispühl School of Computer Science McGill University. Based on slides from (Goodrich & Tamassia, 2004)

HOWDY! WELCOME TO CSCE 221 DATA STRUCTURES AND ALGORITHMS

cs Java: lecture #6

CS61B Lecture #19. Last modified: Mon Oct 13 12:02: CS61B: Lecture #19 1

Project 2 (Deques and Randomized Queues)

Data Structures and Algorithms. Chapter 5. Dynamic Data Structures and Abstract Data Types

CIS 110 Introduction to Computer Programming Summer 2017 Final. Recitation # (e.g., 201):

Outline and Reading. The Stack ADT ( 2.1.1) Applications of Stacks ( 2.1.1) Array-based implementation ( 2.1.1) Growable array-based stack ( 1.

Introduction to Computing II (ITI 1121) FINAL EXAMINATION

[2:3] Linked Lists, Stacks, Queues

Recursive Objects. Singly Linked List (Part 2)

Data Structures and Algorithms, Winter term 2018 Practice Assignment 3

COE 312 Data Structures. Welcome to Exam II Monday November 23, Instructor: Dr. Wissam F. Fawaz

Class 26: Linked Lists

CSC 172 Data Structures and Algorithms. Lecture #9 Spring 2018

Recap. List Types. List Functionality. ListIterator. Adapter Design Pattern. Department of Computer Science 1

10/1/2018 Data Structure & Algorithm. Circularly Linked List Doubly Linked List Priority queues Heaps

Implementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations

Abstract Data Types. Data Str. Client Prog. Add. Rem. Find. Show. 01/22/04 Lecture 4 1

Unit 4 Basic Collections

1/22/13. Queue? CS 200 Algorithms and Data Structures. Implementing Queue Comparison implementations. Photo by David Jump 9. Colorado State University

Transcription:

Solutions to a few of the review problems: Problem 1 The interface Deque can have array based and linked implementations. Partial versions of implementation classes follow. Supply implementations for the method addrear for both. class ArrayDeque implements Deque // circular array based { private Object data[]; private int front, rear, size, capacity; public ArrayDeque() { capacity = 1000; data = new Object[capacity]; front = size = 0; rear = 1; // method code omitted here class DNode { private Object data; private DNode prev, next; // standard constructors, get and set method code omitted here class LinkedDeque implements Deque { private DNode front, rear; private int size; public LinkedDeque() { front = rear = null; size = 0; // method code omitted here (a) Implement the method addrear for the array based class. public void addrear(object x) { if (size == capacity) throw new RuntimeException("Full"); data[rear++] = x; if (rear == capacity) rear = 0; size++; (b) Implement the method addrear for the linked class. public void addrear(object x) { DNode newnode = new Dnode(x, rear, null); if (rear == null) front = newnode; else rear.setnext(newnode); rear = newnode; size++; Problem 2 Write a Java implementation for the following problem. You can make use of whichever of the ADTs Stack, Queue, and Deque that you need. Assume that these ADTs are already implemented, compiled and available in files Stack.class, Queue.class, Deque.class. Input is read as a sequence of strings from the terminal (System.in). The program continues until the special string is found on the input. Input data is stored until one of the special strings +,, 0 is encountered. These special strings cause the stored data to be printed forwards and removed, printed backwards and removed, or removed without printing. For example, if the input is: q w e r + z x c v 0 t y u i p - a s d 0 q w e * the output would be:

q w e r p i u y t import java.util.*; class Prob3 { public static void main(string args[]) { try { Scanner s = new Scanner(System.in); Deque d = new Deque(); while (true) { String x = s.next(); if (x.equals("+")) { while(!d.empty()) System.out.print(d.removeFront() + " "); System.out.println(); else if (x.equals("-")) { while(!d.empty()) System.out.print(d.removeRear() + " "); System.out.println(); else if (x.equals("0")) { while(!d.empty()) d.removerear(); else if (x.equals("*")) { throw new RuntimeException("Done"); else d.addrear(x); catch (Exception e) { Problem 3 (i) Write the Java interface for the ADT Stack. (Just write an interface that specifies methods do not implement the methods.) interface Stack { public Object pop(); public void push(object x); public int size(); public boolean empty(); (ii) Write the Java interface for the ADT Iterator. implement the methods.) interface Iterator { public Object next(); public boolean hasnext(); public void remove(); (iii) Write a client function with title line: (Just write an interface that specifies methods do not public static int count(stack s, Object x) The function returns a count of the number of times the object x is found on the Stack s. When the method ends the Stack should store exactly the same data as at the beginning of the method. However your function will need to alter the Stack data as it runs.

public static int count(stack s, Object x) { Stack temp = new Stack(); int ans = 0; while (!s.empty()) { Object y = s.pop(); if (y.equals(x)) ans++; temp.push(y); while (!temp.empty()) s.push(temp.pop()); return ans; (iv) Write a client function with title line: public static int count(iterator i, Object x) The function returns a count of the number of times the object x is found on the Iterator i. This function can and should empty out the Iterator and should not restore it to its original state. public static int count(iterator i, Object x) { int ans = 0; while (i.hasnext()) { Object y = i.next(); if (y.equals(x)) ans++; return ans; Problem 4 Give useful O-estimates of the run times of the following methods: (a) The method addhead for a singly linked list that has size n. O(1) (b) An efficient method to calculate the power x n (consider the run time as a function of n, the time should be considered as being proportional to the total number of additions, subtractions, multiplications, and divisions performed). O(log(n)) (c) An efficient method to sort an array of n numbers into order. O(nlog(n)) For (d) and (e), consider the following recursive function, in which A represents an integer constant: int f(int n) { if (n <= 0) return 1; int ans = f(n/2) * 2; for (int i = 1; i<= n; i++) for (int j = 1; j <= n; j++) ans += i / j; for (int k = 1; k < A; k++) ans -= f(n/2 - k); return ans; (d) In the case where A = 3 estimate the run time of f(n). O(n 2 ) (e) In the case where A = 4 estimate the run time of f(n). O(n 2 log(n))

Problem 5 The class Queue is to be programmed with an array based implementation. A partial version of the implementation follows. The two most important methods have been omitted. class Queue { private Object data[]; private int front, rear, size; public Queue() { data = new Object[100]; front = rear = size = 0; public int size() { return size; public boolean empty() { return size == 0; // methods omitted here (a) Identify the two missing methods. For each give the name, parameters and return type. public Object dequeue(); public void enqueue(object x); (b) Give a complete implementation of ONE of the two missing Queue methods. (You can choose either of them.) public void enqueue(object x) { if (size() == 100) throw new RuntimeException("Queue Full"); data[rear++] = x; if (rear == 100) rear = 0; size ++; public Object dequeue() { if (empty()) throw new RuntimeException("Queue Empty"); Object answer = data[front++]; if (front == 100) front = 0; size --; return answer; Problem 6 Give useful O-estimates (in terms of the quantity n) for the run times of the following methods: (a) The method removet ail for a singly linked list that has size n. O(n) (b) An efficient method to sort an array that contains n items of data. O(nlog(n)) For (c) and (d), consider the following recursive method, in which pow calculates either the square (in part (c)) or the cube (in part (d)) of its parameter. int f(int n) { if (n <= 0) return 1; int ans = 0; for (int i = 1; i<= pow(n); i++) ans += i * i; return ans - f(n/2) + f(n/2-1) - f(n/2-2) + f(n/2-3);

(c) In the case where pow(n) calculates n 2, estimate the run time of f(n). O(n 2 log(n)) (d) In the case where pow(n) calculates n 3, estimate the run time of f(n). O(n 3 ) (e) Give a O-estimate for the run time of the following method. Here, the parameter n represents the number of array elements to be considered: int estimatemedian(int a[], int n, int startat) { if (n == 1) return a[startat]; int half = n / 2; int med1 = estimatemedian(a, half, startat); int med2 = estimatemedian(a, n - half, startat + half); return (med1 + med2) / 2; O(n) Problem 7 Suppose that a singly linked list is implemented as a class LinkedList that has a single instance variable head of class Node. No sentinels are used, so that head.data is the first object in the list, and the last node is indicated by a next link with value null. Write a method def red() of the class LinkedList that removes all entries (and their nodes) that store data equal to the string Freddy. For example, if the list l stores the data: A, B, C, D, E, F reddy, G, F reddy, H a call of the method l.def red() would leave it as: A, B, C, D, E, G, H. public void defred() { Node cursor = head; while (cursor!= null && cursor.getnext()!= null) { if (cursor.getnext().getdata().equals("freddy")) cursor.setnext(cursor.getnext().getnext()); else cursor = cursor.getnext(); if (head!= null && head.getdata().equals("freddy")) head = head.getnext(); Problem 8 A partial array based implementation of a Deque (with capacity 100) follows. The four most important methods have been omitted. class Deque { private Object data[]; private int front, rear, size; public ArrayDeque() { data = new Object[100]; front = size = 0; rear = 1; public int size() { return size; public boolean empty() { return size == 0; // methods omitted (a) Identify the four missing methods. For each give a reasonable name, parameters and return type.

public Object removefront(); public Object removerear(); public void addfront(object x); public void addrear(object x); (b) Give a complete implementation of ONE of the four missing Deque methods. (You can choose any one of them.) public void addfront(object x) { if (size() == 100) throw new RuntimeException("Deque Full"); data[front--]= x; if (front < 0) front = 99; size ++; public void addrear(object x) { if (size() == 100) throw new RuntimeException("Deque Full"); data[rear++] = x; if (rear == 100) rear = 0; size ++; public Object removefront() { if (empty()) throw new RuntimeException("Deque Empty"); front = front + 1; if (front == capacity) front = 0; size --; return data[front]; public Object removerear() { if (empty()) throw new RuntimeException("Deque Empty"); rear = rear - 1; if (rear == -1) rear = capacity - 1; size --; return data[rear]; (c) What additions would need to be made to the Java implementation to make the Deque iterable. (Identify one change to the title line for the class and one change within the body of the class.) The title line should be changed to: class Deque implements Iterable {... and a method with title public Iterator iterator() {... should be added to the body of the class (Extra credit) Implement the changes that you specified in (c), and give an implementation of an appropriate Iterator class, if this is needed. (Write your implementation on the facing page.)

public Iterator iterator() { Vector v = new Vector(); int cursor = front; for (int i = 0; i < size; i++) { cursor++; if (cursor == capacity) cursor = 0; v.add(data[cursor]); return v.iterator(); Problem 9 Write a complete DList adapter implementation of the interface Deque. (Do not supply any implementation for the classes DNode and DList.) Assume that a doubly linked list is available and has been implemented as the class DList. The implementation of class Dlist uses an auxiliary class DNode and provides a constructor and the methods size, isempty, getf irst, getlast, getbef ore, getaf ter, addf irst, addlast, addbef ore, addaf ter, and remove as discussed in class. class DListAdapterDeque implements Deque { private DList l; public DListAdapterDeque() { l = new DList(); public int size() { return l.size(); public boolean empty() { return size() == 0; public void addfront(object x) { l.addfirst(x); public void addrear(object x) { l.addlast(x); public Object removefront() { return l.remove(l.getfirst()); public Object removerear() { return l.remove(l.getlast()); Problem 10 Give useful O-estimates of the run times of the following methods: (a) The method addt ail for a singly linked list that has size n. O(1). (b) An efficient method to calculate the power x n (consider the run time as a function of n). O(logn). You could make a case that the answer should be O(n), and this will be accepted.

(c) An efficient method to calculate the n th Fibonacci number. O(n). You could make a case that the answer should be O(logn), and this will be accepted. For (d) and (e), consider the following recursive function, in which A represents an integer constant: int f(int n) { if (n <= 0) return 1; int ans = 0; for (int i = 1; i<= n; i++) for (int j = 1; j <= i; j++) ans += i * j; for (int k = 1; k <= A; k++) ans -= f(n/2 - k); return ans; (d) In the case where A = 1 estimate the run time of f(n). Overhead h(n) = O(n 2 ), Effective recursive cost r(n) = n log2(1) = n 0. By the Master theorem, the runtime t(n) satisfies t(n) = O(n 2 ). (e) In the case where A = 4 estimate the run time of f(n). Overhead h(n) = O(n 2 ), Effective recursive cost r(n) = n log2(4) = n 2. By the Master theorem, the runtime t(n) satisfies t(n) = O(n 2 logn). Problem 11 Consider the following partial implementation of a circular list of singly linked nodes. public class CircularList { private Node cursor; public CircularList() { cursor = null; public boolean isempty() {return cursor == null; public void advance() { cursor = cursor.getnext(); public void addafter(object d) { CODE OMITTED TO SAVE SPACE public void addbefore(object d) { addafter(d); swapdata(cursor, cursor.getnext()); cursor = cursor.getnext(); private void swapdata(node n, Node m) { // helper method for addbefore and remove Object temp = n.getdata(); n.setdata(m.getdata()); m.setdata(temp); public Object remove() { CODE OMITTED HERE public String tostring() { CODE OMITTED HERE Supply an implementation for the missing method tostring. The output from your method should match the following format (which indicates a circular list with size 3, stored data A, B, C and the cursor at item A): A -> B -> C -> public String tostring() { if (cursor == null) return ""; String ans = cursor.getdata() + " ->"; Node n = cursor.getnext(); while (n!= cursor) { ans += n.getdata(); ans += "->";

n = n.getnext(); return ans; (Extra credit) Write an implementation of the method remove. (Hint: Use the swapdata() method, and apply the trick used in addbefore().) public Object remove() { if (cursor == null) throw new RuntimeException("Empty"); Object answer = cursor.getdata(); if (cursor.getnext() == cursor) { cursor = null; return answer; swapdata(cursor, cursor.getnext()); cursor.setnext(cursor.getnext().getnext()); return answer; Problem 12 Write Java interfaces for the following ADTs. (For each part, just write an interface that specifies methods do not implement these methods.) (i) Stack interface Stack { public Object pop(); public void push(object x); (ii) Queue interface Queue{ public Object remove(); public void add(object x); (iii) Deque interface Deque{ public Object removefirst(); public Object removelast(); public void addfirst(object x); public void addlast(object x); Problem 13 Write a Java implementation for the following problem. You can make use of whichever of the ADTs Stack, Queue, and Deque that you need. Assume that these ADTs are already implemented, compiled and available in files Stack.class, Queue.class, Deque.class. Input is read from the terminal (System.in). All input Strings are read and stored. The input Strings BEGIN, END, and PRINT have special meanings. Whenever a String that matches PRINT is read, all stored strings that appear after the last stored BEGIN string are printed (in the same order that they were entered). These printed strings together with their enclosing BEGIN and PRINT strings are removed from storage. If there is no stored BEGIN string an Exception should be thrown. When the string END is read, the program terminates. For example, if the input is:

BEGIN is This PRINT BEGIN easy. PRINT END the output would be: is This easy. Or if the input is: BEGIN is This BEGIN easy. PRINT PRINT ignore END the output would be easy. is This import java.util.*; public class Prob2 { public static void main(string args[]) { Stack s = new Stack(); Scanner i = new Scanner(System.in); String w; while (i.hasnext()) { w = i.next(); if (w.equals("end")) System.exit(0); if (!w.equals("print")) s.push(w); else { // process a PRINT instruction Stack temp = new Stack(); while (!s.empty()) { w = (String) s.pop(); if (!w.equals("begin")) temp.push(w); else { while (!temp.empty()) System.out.print((String) temp.pop() + " "); break; if (!w.equals("begin")) throw new RuntimeException(); Problem 14 Suppose that a doubly linked list is implemented as a class DoublyLinkedList that uses sentinel doubly linked nodes header and trailer and no other instance variables. Write a method of the class called removemiddle that removes either the middle node from a list of odd length, or the middle two nodes from a list of even length. The method should throw an exception if the required nodes do not exist. Give a O-estimate for the run time of your method in terms of the number n of elements in the list. public void removemiddle() { if (header.getnext() == trailer) throw new RuntimeException("Empty"); removerecursive(header, trailer);

private void removerecursive(dnode h, DNode t) { if (h == t h.getnext() == t) { DNode downone = h.getprev(); DNode upone = t.getnext(); downone.setnext( upone); upone.setprev(downone); else removerecursive(h.getnext(), t.getprev()); The run time of this method is O(n). Problem 15 Give O-estimate for the run times of the following methods in terms of the parameter called n. At least one of the methods is inefficient, identify this method and give a different implementation that has a significantly better run time (for large values of n). (a) public static int fibonacci(int n) { if (n <= 0) return 0; int last = 0, current = 1, index = 1, temp; while (index++ < n) { temp = last + current; last = current; current = temp; return current; (b) public static int factorial(int n) { if (n <= 0) return 1; return n * factorial(n - 1); (c) public static double power(double x, int n) { double ans = 1.0; int index = 0; while (index++ < n) ans = ans * x; return ans; (d) Which of these methods is inefficient? Give an efficient implementation of this method. Problem 16 Write a Java implementation for the following problem. You can make use of whichever of the ADTs Stack, Queue, and Deque that you need. Assume that these ADTs are already implemented, compiled and available in files Stack.class, Queue.class, Deque.class. Input is read from the terminal (System.in). All input Strings are read and stored. The input String PRINT has a special meaning. Whenever a String that matches PRINT is read, the first stored string and the last 5 stored strings are printed. If there are not enough strings, the program should terminate as soon as it runs out of strings. For example, if the input is: 1 2 3 4 5 6 7 8 PRINT 9 PRINT 10 11 12 13 PRINT the output would be: 1 8 7 6 5 4 2 9 3

Problem 17 Suppose that a singly linked list is implemented as a class LinkedList that has a single instance variable head of class Node. No sentinels are used, so that head.data is the first object in the list, and the last node is indicated by a next link with value null. Write a method of the class called oddentries that removes all entries at even positions of the list. For example, if the list starts as 1, 2, 3, 4, 5 the method would turn it into 1, 3, 5. Problem 18 The class Queue is to be implemented as a doubly linked list of DNode objects. Each DNode is a standard doubly linked node, with 3 instance variables Object data, DNode next, and DNode prev. As usual, DNode has 3 get methods and 3 set methods (one for each instance variable) and a 3 argument constructor. A partial implementation of the class Queue follows. The two most important methods have been omitted. class Queue { private DNode front, rear; private int size; public Queue() {front = rear = null; size = 0; public int size() { return size; public boolean empty() { return size == 0; (a) Identify the two missing methods. For each give the name, parameters and return type. public Object dequeue() public void enqueue(object x) (b) Give a complete implementation of ONE of the two missing Queue methods. (You can choose either of them.) public Object dequeue() { if (empty()) throw new RuntimeException(); Object answer = front.getdata(); front = front.getnext(); size--; if (size!= 0) front.setprev(null); else rear = null; return answer; public void enqueue(object x) { DNode newrear = new DNode(x, rear, null); if (rear!= null) rear.setnext(newrear); else front = newrear; rear = newrear; size++; // data, prev, next Problem 19 Write a Java program to solve the following problem. You can make use of whichever of the ADTs Stack, Queue, and Deque that you need. Assume that these ADTs are already implemented, compiled and available in files Stack.class, Queue.class, Deque.class. Input is read, one String at a time, from a file input.txt. Input Strings are stored as they are read. The input Strings!R and!f have special meanings. Whenever a String that matches!r is read, all stored strings are removed from storage and printed in reverse order of input. Whenever a String that matches!f is read, every second stored string is printed in order of input, and the program terminates. The program also terminates without further output when the input file ends. For example, if the input is: Reverse these!r and half these words are printed forward!f but this is lost!r the output would be:

these Reverse and these are forward import java.util.*; import java.io.*; public class Prob2 { public static void main(string args[]) { try { Deque d = new Deque(); Scanner in = new Scanner(new File("input.txt")); String s; while (in.hasnext()) { s = in.next(); if (s.equals("!r")) { while (!d.empty()) { s = (String) d.removerear(); System.out.print(s + " "); System.out.println(); else if (s.equals("!f")) { while (!d.empty()) { s = (String) d.removefront(); System.out.print(s + " "); if (!d.empty()) d.removefront(); System.out.println(); break; else d.addrear(s); catch (Exception e) { Problem 20 A linked stack is implemented using a standard Node class as follows: import java.util.*; class stack implements Iterable { private Node top; private int size; public stack() { top = null; size = 0; public Object pop() { if (size == 0) throw new RuntimeException(""); Object answer = top.getdata(); top = top.getnext(); size --; return answer; public void push(object x) { Node newnode = new Node(x, top); top = newnode; size++;

// the iterator method is missing Write a class StackIterator to implement objects that can be returned by the stack iterator. Also write the missing stack method called iterator. You can decide whether the iterator will run through the data in the stack in LIFO or FIFO order (one choice is much easier). (a) The StackIterator class: class StackIterator implements Iterator { private Node current; public StackIterator(Node c) { current = c; public Object next() { Object answer = current.getdata(); current = current.getnext(); return answer; public boolean hasnext() { return current!= null; public void remove() {; (b) The iterator method in the stack class: public Iterator iterator() { return new StackIterator(top);