7.36 Suppose we want to extend the PositionalList interface to include a method,
ID: 3775798 • Letter: 7
Question
7.36 Suppose we want to extend the PositionalList interface to include a method,
positionAtIndex(i), that returns the position of the element having index i (or
throws an IndexOutOfBoundsException, if warranted). Show how to implement
this method, using only existing methods of the PositionalList interface,
by traversing the appropriate number of steps from the front of the list.
Explain how any implementation of the PositionalList ADT can be made to support
all methods of the List ADT, described in Section 7.1, assuming an implementation
is given for the positionAtIndex(i) method, proposed in Exercise C-
7.36.
position list:
Public position positionAtIndex(index i)
{
If ( j< 0 || j >= size())
Throw new IndexOutOfBoundsException(“ Invalid index");
Position t = first();
For(int k= 0; k<j; k++)
T= after(t);
Return t;
}
Explanation / Answer
public position positionAtIndex(int j)
{
if ( j < 0 || j >= size())
throw new IndexOutOfBoundsException("Invalid index");
Position t = first(); // Get first position
for(int k = 0; k < j; k++) // iterate j - 1 number of times to get to jth position
t = after(t); // move one step next
return t; // return the position at jth index
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.