id
int64
0
25.6k
text
stringlengths
0
4.59k
20,900
efficient method for computing each of partial sums what is the running time of this methodfor , - draw visual justification of proposition analogous to that of figure (bfor the case when is odd - an array contains unique integers in the range [ , that isthere is one number from this range that is not in design an ( )-time algorithm for finding that number you are only allowed to use ( additional space besides the array itself - let be set of lines in the plane such that no two are parallel and no three meet in the same point showby inductionthat the lines in determine th( intersection points - show that the summation is (nlognc- an evil king has bottles of wineand spy has just poisoned one of them unfortunatelythey don' know which one it is the poison is very deadlyjust one drop diluted even billion to one will still kill even soit takes full month for the poison to take effect design scheme for determining exactly which one of the wine bottles was poisoned in just one month' time while expending (logntaste testers - suppose that each row of an array consists of ' and ' such thatin any row of all the ' come before any ' in that row assuming is already in memorydescribe method running in (ntime (not ( timefor finding the row of that contains the most ' -
20,901
matrix recall that the product ab is defined so that [ [jwhat is the running time of your methodc- suppose each row of an array consists of ' and ' such thatin any row of all the ' come before any ' also suppose that the number of ' in row is at least the number in row for , assuming is already in memorydescribe method running in (ntime (not ( )for counting the number of ' in - describe recursive method for computing the nth harmonic numberprojects - implement prefixaverages and prefixaverages from section and perform an experimental analysis of their running times visualize their running times as function of the input size with log-log chart - perform careful experimental analysis that compares the relative running times of the methods shown in code fragments notes the big-oh notation has prompted several comments about its proper use [ knuth [ defines it using the notation (no( ( ))but says this "equalityis only "one way we have chosen to take more standard view of equality and view the big-oh notation as setfollowing brassard [ the reader interested in studying average-case analysis is referred to the book by vitter and flajolet [ we found the story about archimedes in [ for some additional mathematical toolsplease refer to appendix
20,902
stacks and queues contents
20,903
the stack abstract data type simple array-based stack implementation implementing stack with generic linked list reversing an array using stack matching parentheses and html tags queues the queue abstract data type asimple array-based queue implementation
20,904
implementing queue with generic linked list round robin schedulers double-ended queues the deque abstract data type implementing deque exercises java datastructures net stacks stack is collection of objects that are inserted and removed according to the lastin first-out (lifoprinciple objects can be inserted into stack at any timebut only the most recently inserted (that is"last"object can be removed at any time the name "stackis derived from the metaphor of stack of plates in spring-loadedcafeteria plate dispenser in this casethe fundamental operations involve the "pushingand "poppingof plates on the stack when we need new plate from the dispenserwe "popthe top plate off the stackand when we add platewe "pushit
20,905
metaphor would be pez(rcandy dispenserwhich stores mint candies in springloaded container that "popsout the top-most candy in the stack when the top of the dispenser is lifted (see figure stacks are fundamental data structure they are used in many applicationsincluding the following figure schematic drawing of pez(rdispensera physical implementation of the stack adt (pez(ris registered trademark of pez candyinc example internet web browsers store the addresses of recently visited sites on stack each time user visits new sitethat site' address is "pushedonto the stack of addresses the browser then allows the user to "popback to previously visited sites using the "backbutton example text editors usually provide an "undomechanism that cancels recent editing operations and reverts to former states of document this undo operation can be accomplished by keeping text changes in stack the stack abstract data type stacks are the simplest of all data structuresyet they are also among the most importantas they are used in host of different applications that include many more sophisticated data structures formallya stack is an abstract data type (adtthat supports the following two methods
20,906
pop()remove from the stack and return the top element on the stackan error occurs if the stack is empty additionallylet us also define the following methodssize()return the number of elements in the stack isempty()return boolean indicating if the stack is empty top()return the top element in the stackwithout removing itan error occurs if the stack is empty example the following table shows series of stack operations and their effects on an initially empty stack of integers operation output stack contents push( ( push( ( pop( ( push( ( pop(
20,907
( top( ( pop( (pop("error(isempty(true (push( ( push( ( push( ( push(
20,908
size( ( pop( ( push( ( pop( ( pop( ( stack interface in java because of its importancethe stack data structure is included as "built-inclass in the java util package of java class java util stack is data structure that stores generic java objects and includesamong othersthe methods push()pop()peek((equivalent to top())size()and empty((equivalent to isempty()methods pop(and peek(throw exception emptystackexception if they are called on an empty stack while it is convenient to just use the built-in class java util stackit is instructive to learn how to design and implement stack "from scratch implementing an abstract data type in java involves two steps the first step is the definition of java application programming interface (api)or simply interfacewhich describes the names of the methods that the adt supports and how they are to be declared and used
20,909
instancethe error condition that occurs when calling method pop(or top(on an empty stack is signaled by throwing an exception of type emptystackexceptionwhich is defined in code fragment code fragment exception thrown by methods pop(and top(of the stack interface when called on an empty stack complete java interface for the stack adt is given in code fragment note that this interface is very general since it specifies that elements of any given class (and its subclassescan be inserted into the stack it achieves this generality by using the concept of generics (section for given adt to be of any usewe need to provide concrete class that implements the methods of the interface associated with that adt we give simple implementation of the stack interface in the following subsection code fragment interface stack documented with comments in javadoc style (section note also the use of the generic parameterized typeewhich implies that stack can contain elements of any specified class
20,910
we can implement stack by storing its elements in an array specificallythe stack in this implementation consists of an -element array plus an integer variable that gives the the index of the top element in array (see figure figure implementing stack with an array the top element in the stack is stored in the cell [trecalling that arrays start at index in javawe initialize to - and we use this value for to identify an empty stack likewisewe can use to determine the number of elements ( we also introduce new exceptioncalled fullstackexceptionto signal the error that arises if we try to insert new element into full array exception fullstackexception is specific to this implementation and is not defined in the stack adthowever we give the details of the array-based stack implementation in code fragment code fragment array of given sizen implementing stack using an
20,911
the correctness of the methods in the array-based implementation follows immediately from the definition of the methods themselves there isneverthelessa mildly interesting point here involving the implementation of the pop method note that we could have avoided resetting the old [tto null and we would still have correct method there is trade-off in being able to avoid this assignment should we be thinking about implementing these algorithms in javahowever the trade-off involves the java garbage collection mechanism that searches memory for objects that are no longer referenced by active objectsand reclaims their space for future use (for more detailssee section let [tbe the top element before the pop method is called by making [ta null reference
20,912
if there are no other active references to ethen the memory space taken by will be reclaimed by the garbage collector table shows the running times for methods in realization of stack by an array each of the stack methods in the array realization executes constant number of statements involving arithmetic operationscomparisonsand assignments in additionpop also calls isemptywhich itself runs in constant time thusin this implementation of the stack adteach method runs in constant timethat isthey each run in ( time table performance of stack realized by an array the space usage is ( )where is the size of the arraydetermined at the time the stack is instantiated note that the space usage is independent from the number < of elements that are actually in the stack method time size ( is empty ( top ( push ( pop ( concrete java implementation of the pseudo-code of code fragment with java class arraystack implementing the stack interfaceis given in code fragments and unfortunatelydue to space considerationswe omit most
20,913
remainder of this book note that we use symbolic namecapacityto specify the capacity of the array this allows us to specify the capacity of the array in one place in our code and have that value reflected throughout code fragment array-based java implementation of the stack interface (continues in code fragment
20,914
array-based stack (continued from code fragment
20,915
belowwe show the output from the above arraystack program note thatthrough the use of generic typeswe are able to create an arraystack for storing integers and another arraystack that stores character strings new arraystack areturns null resultsize isempty truestack[ push( )returns null resultsize isempty falsestack[ pop()returns resultsize isempty truestack[ push( )returns null resultsize isempty falsestack[ pop()returns resultsize isempty truestack[new arraystack breturns null resultsize isempty truestack[ push("bob")returns null resultsize isempty falsestack[bobb push("alice")returns null resultsize isempty falsestack[bobaliceb pop()returns alice resultsize isempty falsestack[bobb push("eve")returns null resultsize isempty falsestack[bobevea drawback with the array-based stack implementation
20,916
implementation has one negative aspect--it must assume fixed upper boundcapacityon the ultimate size of the stack in code fragment we chose the capacity value , more or less arbitrarily an application may actually need much less space than thiswhich would waste memory alternativelyan application may need more space than thiswhich would cause our stack implementation to generate an exception as soon as client program tries to push its , st object on the stack thuseven with its simplicity and efficiencythe array-based stack implementation is not necessarily ideal fortunatelythere is another implementationwhich we discuss nextthat does not have size limitation and use space proportional to the actual number of elements stored in the stack stillin cases where we have good estimate on the number of items needing to go in the stackthe array-based implementation is hard to beat stacks serve vital role in number of computing applicationsso it is helpful to have fast stack adt implementation such as the simple array-based implementation implementing stack with generic linked list in this sectionwe explore using singly linked list to implement the stack adt in designing such an implementationwe need to decide if the top of the stack is at the head or at the tail of the list there is clearly best choice herehoweversince we can insert and delete elements in constant time only at the head thusit is more efficient to have the top of the stack at the head of our list alsoin order to perform operation size in constant timewe keep track of the current number of elements in an instance variable rather than use linked list that can only store objects of certain typeas we showed in section we would likein this caseto implement generic stack using generic linked list thuswe need to use generic kind of node to implement this linked list we show such node class in code fragment code fragment class nodewhich implements generic node for singly linked list
20,917
java implementation of stackby means of generic singly linked listis given in code fragment all the methods of the stack interface are executed in constant time in addition to being time efficientthis linked list implementation has space requirement that is ( )where is the current number of elements in the stack thusthis implementation does not require that new exception be created to handle size overflow problems we use an instance variable top to refer to the head of the list (which points to the null object if the list is emptywhen we push new element on the stackwe simply create new node for ereference from vand insert at the head of the list likewisewhen we pop an element from the stackwe simply remove the node at the head
20,918
elements at the head of the list code fragment class nodestackwhich implements the stack interface using singly linked listwhose nodes are objects of class node from code fragment reversing an array using stack we can use stack to reverse the elements in an arraythereby producing nonrecursive algorithm for the array-reversal problem introduced in section the basic idea is simply to push all the elements of the array in order into stack
20,919
code fragment we give java implementation of this algorithm incidentallythis method also illustrates how we can use generic types in simple application that uses generic stack in particularwhen the elements are popped off the stack in this examplethey are automatically returned as elements of the typehencethey can be immediately returned to the input array we show an example use of this method in code fragment code fragment generic method that reverses the elements in an array of type objectsusing stack declared using the stack interface code fragment test of the reverse method using two arrays
20,920
in this subsectionwe explore two related applications of stacksthe first of which is for matching parentheses and grouping symbols in arithmetic expressions arithmetic expressions can contain various pairs of grouping symbolssuch as parentheses"(and ")braces"{and "}brackets"[and "]floor function symbolsceiling function symbolsand ,and and each opening symbol must match with its corresponding closing symbol for examplea left bracket"[,must match with corresponding right bracket"],as in the following expression[( ( )
20,921
correct)()){([)])correct(()()){([)])})incorrect)()){([)])incorrect({[])incorrectwe leave the precise definition of matching of grouping symbols to exercise - an algorithm for parentheses matching an important problem in processing arithmetic expressions is to make sure their grouping symbols match up correctly we can use stack to perform the matching of grouping symbols in an arithmetic expression with single left-toright scan the algorithm tests that left and right symbols match up and also that the left and right symbols are both of the same type suppose we are given sequence - where each is token that can be grouping symbola variable namean arithmetic operatoror number the basic idea behind checking that the grouping symbols in match correctlyis to process the tokens in in order each time we encounter an opening symbolwe push that symbol onto sand each time we encounter closing symbolwe pop the top symbol from the stack (assuming is not emptyand we check that these two symbols are of the same type if the stack is empty after we have processed the whole sequencethen the symbols in match assuming that the push and pop operations are implemented to run in constant timethis algorithm runs in ( )that is lineartime we give pseudo-code description of this algorithm in code fragment code fragment algorithm for matching grouping symbols in an arithmetic expression
20,922
another application in which matching is important is in the validation of html documents html is the standard format for hyperlinked documents on the internet in an html documentportions of text are delimited by html tags simple opening html tag has the form "and the corresponding closing tag has the form commonly used html tags include bodydocument body section header centercenter justify pparagraph olnumbered (orderedlist lilist item ideallyan html document should have matching tagsalthough most browsers tolerate certain number of mismatching tags we show sample html document and possible rendering in figure
20,923
document(bits rendering fortunatelymore or less the same algorithm as in code fragment can be used to match the tags in an html document in code fragments and we give java program for matching tags in an html document read from standard input for simplicitywe assume that all tags are the simple opening or closing tags defined above and that no tags are formed incorrectly code fragment complete java program for testing if an html document has fully matching tags (continues in code fragment
20,924
matching tags in an html document (continued from method ishtmlmatched uses stack to store the names of the opening tags seen so farsimilar to how the stack was used in code fragment method parsehtml uses scanner to extract the tags from the html documentusing the pattern "]*>,which denotes string that starts with '<'followed by zero or more characters that are not '>'followed by '>
20,925
queue is collection of objects that are inserted and removed according to the firstin first-out (fifoprinciple that iselements can be inserted at any timebut only the element that has been in the queue the longest can be removed at any time we usually say that elements enter queue at the rear and are removed from the front the metaphor for this terminology is line of people waiting to get on an amusement park ride people waiting for such ride enter at the rear of the line and get on the ride from the front of the line the queue abstract data type formallythe queue abstract data type defines collection that keeps objects in sequencewhere element access and deletion are restricted to the first element in the sequencewhich is called the front of the queueand element insertion is restricted to the end of the sequencewhich is called the rear of the queue this restriction enforces the rule that items are inserted and deleted in queue according to the first-in first-out (fifoprinciple the queue abstract data type (adtsupports the following two fundamental methodsenqueue( )insert element at the rear of the queue dequeue()remove and return from the queue the object at the frontan error occurs if the queue is empty additionallysimilar to the case with the stack adtthe queue adt includes the following supporting methodssize()return the number of objects in the queue isempty()return boolean value that indicates whether the queue is empty front()returnbut do not removethe front object in the queuean error occurs if the queue is empty example the following table shows series of queue operations and their effects on an initially empty queue of integer objects for simplicitywe use integers instead of integer objects as arguments of the operations operation output front rear
20,926
( enqueue( ( dequeue ( enqueue( ( dequeue ( front ( dequeue (dequeue"error(isempty
20,927
(enqueue( ( enqueue( ( size( ( enqueue( ( enqueue( ( dequeue ( example applications there are several possible applications for queues storestheatersreservation centersand other similar services typically process customer requests according to the fifo principle queue would therefore be logical choice for data structure to handle transaction processing for such applications for exampleit would be natural choice for handling calls to the reservation center of an airline or to the box office of theater
20,928
java interface for the queue adt is given in code fragment this generic interface specifies that objects of arbitrary object types can be inserted into the queue thuswe don' have to use explicit casting when removing elements note that the size and isempty methods have the same meaning as their counterparts in the stack adt these two methodsas well as the front methodare known as accessor methodsfor they return value and do not change the contents of the data structure code fragment interface queue documented with comments in javadoc style
20,929
we present simple realization of queue by means of an arrayqof fixed capacitystoring its elements since the main rule with the queue adt is that we insert and delete objects according to the fifo principlewe must decide how we are going to keep track of the front and rear of the queue
20,930
letting [ be the front of the queue and then letting the queue grow from there this is not an efficient solutionhoweverfor it requires that we move all the elements forward one array cell each time we perform dequeue operation such an implementation would therefore take (ntime to perform the dequeue methodwhere is the current number of objects in the queue if we want to achieve constant time for each queue methodwe need different approach using an array in circular way to avoid moving objects once they are placed in qwe define two variables and rwhich have the following meaningsf is an index to the cell of storing the first element of the queue (which is the next candidate to be removed by dequeue operation)unless the queue is empty (in which case rr is an index to the next available array cell in initiallywe assign which indicates that the queue is empty nowwhen we remove an element from the front of the queuewe increment to index the next cell likewisewhen we add an elementwe store it in cell [rand increment to index the next available cell in this scheme allows us to implement methods frontenqueueand dequeue in constant timethat iso( time howeverthere is still problem with this approach considerfor examplewhat happens if we repeatedly enqueue and dequeue single element different times we would have if we were then to try to insert the element just one more timewe would get an array-out-of-bounds error (since the valid locations in are from [ to [ ])even though there is plenty of room in the queue in this case to avoid this problem and be able to utilize all of the array qwe let the and indices "wrap aroundthe end of that iswe now view as "circular arraythat goes from [ to [ and then immediately back to [ again (see figure figure using array in circular fashion(athe "normalconfiguration with < (bthe "wrapped aroundconfiguration with the cells storing queue elements are highlighted
20,931
array implementing this circular view of is actually pretty easy each time we increment or rwe compute this increment as "( mod nor "( mod ,respectively recall that operator "modis the modulo operatorwhich is computed by taking the remainder after an integral division for example divided by is with remainder so mod specificallygiven integers and such that > and we have mod / that isif mod ythen there is nonnegative integer qsuch that qy java uses "%to denote the modulo operator by using the modulo operatorwe can view as circular array and implement each queue method in constant amount of time (that iso( timewe describe how to use this approach to implement queue in code fragment code fragment implementation of queue using circular array the implementation uses the modulo operator to "wrapindices around the end of the array and it also includes two instance variablesf and rwhich index the front of the queue and first empty cell after the rear of the queue respectively
20,932
first consider the situation that occurs if we enqueue objects into without dequeuing any of them we would have rwhich is the same condition that occurs when the queue is empty hencewe would not be able to tell the difference between full queue and an empty one in this case fortunatelythis is not big problemand number of ways for dealing with it exist the solution we describe here is to insist that can never hold more than objects this simple rule for handling full queue takes care of the final problem with our implementationand leads to the pseudo-coded descriptions of the queue methods given in code fragment note our introduction of an implementation-specific exceptioncalled fullqueueexceptionto signal that no more elements can be inserted in the queue also note the way we compute the size of the queue by means of the expression ( rmod
20,933
in the "wrapped aroundconfiguration (when fthe java implementation of queue by means of an array is similar to that of stackand is left as an exercise ( - table shows the running times of methods in realization of queue by an array as with our array-based stack implementationeach of the queue methods in the array realization executes constant number of statements involving arithmetic operationscomparisonsand assignments thuseach method in this implementation runs in ( time table performance of queue realized by an array the space usage is ( )where is the size of the arraydetermined at the time the queue is created note that the space usage is independent from the number of elements that are actually in the queue method time size ( isempty ( front ( enqueue ( dequeue ( as with the array-based stack implementationthe only real disadvantage of the array-based queue implementation is that we artificially set the capacity of the queue to be some fixed value in real applicationwe may actually need more or
20,934
array-based implementation is quite efficient implementing queue with generic linked list we can efficiently implement the queue adt using generic singly linked list for efficiency reasonswe choose the front of the queue to be at the head of the listand the rear of the queue to be at the tail of the list in this waywe remove from the head and insert at the tail (why would it be bad to insert at the head and remove at the tail?note that we need to maintain references to both the head and tail nodes of the list rather than go into every detail of this implementationwe simply give java implementation for the fundamental queue methods in code fragment code fragment methods enqueue and dequeue in the implementation of the queue adt by means of singly linked listusing nodes from class node of code fragment
20,935
in ( time we also avoid the need to specify maximum size for the queueas was done in the array-based queue implementationbut this benefit comes at the expense of increasing the amount of space used per element stillthe methods in the singly linked list queue implementation are more complicated than we might likefor we must take extra care in how we deal with special cases where the queue is empty before an enqueue or where the queue becomes empty after dequeue round robin schedulers popular use of the queue data structure is to implement round robin schedulerwhere we iterate through collection of elements in circular fashion and "serviceeach element by performing given action on it such schedule is usedfor exampleto fairly allocate resource that must be shared by collection of clients
20,936
various applications running concurrently on computer we can implement round robin scheduler using queueqby repeatedly performing the following steps (see figure ) dequeue( service element enqueue(efigure the three iterative steps for using queue to implement round robin scheduler the josephus problem in the children' game "hot potato, group of children sit in circle passing an objectcalled the "potato,around the circle the potato begins with starting child in the circleand the children continue passing the potato until leader rings bellat which point the child holding the potato must leave the game after handing the potato to the next child in the circle after the selected child leavesthe other children close up the circle this process is then continued until there is only one child remainingwho is declared the winner if the leader always uses the strategy of ringing the bell after the potato has been passed timesfor some fixed value kthen determining the winner for given list of children is known as the josephus problem solving the josephus problem using queue we can solve the josephus problem for collection of elements using queueby associating the potato with the element at the front of the queue and storing elements in the queue according to their order around the circle thuspassing the
20,937
after this process has been performed timeswe remove the front element by dequeuing it from the queue and discarding it we show complete java program for solving the josephus problem using this approach in code fragment which describes solution that runs in (nktime (we can solve this problem faster using techniques beyond the scope of this book code fragment complete java program for solving the josephus problem using queue class nodequeue is shown in code fragment
20,938
double-ended queues consider now queue-like data structure that supports insertion and deletion at both the front and the rear of the queue such an extension of queue is called doubleended queueor dequewhich is usually pronounced "deckto avoid confusion with the dequeue method of the regular queue adtwhich is pronounced like the abbreviation " the deque abstract data type the deque abstract data type is richer than both the stack and the queue adts the fundamental methods of the deque adt are as followsaddfirst( )insert new element at the beginning of the deque addlast( )insert new element at the end of the deque removefirst()remove and return the first element of the dequean error occurs if the deque is empty removelast()remove and return the last element of the dequean error occurs if the deque is empty additionallythe deque adt may also include the following support methodsgetfirst()return the first element of the dequean error occurs if the deque is empty getlast()return the last element of the dequean error occurs if the deque is empty size()return the number of elements of the deque isempty()determine if the deque is empty example the following table shows series of operations and their effects on an initially empty deque of integer objects for simplicitywe use integers instead of integer objects as arguments of the operations operation output addfirst(
20,939
addfirst( ( , removefirst( ( addlast( ( , removefirst( ( removelast( (removefirst("error(isempty(true (implementing deque
20,940
linked list to implement deque would be inefficient we can use doubly linked listhoweverto implement deque efficiently as discussed in section inserting or removing elements at either end of doubly linked list is straightforward to do in ( timeif we use sentinel nodes for the header and trailer for an insertion of new element ewe can have access to the node before the place should go and the node after the place should go to insert new element between the two nodes and (either or both of which could be sentinels)we create new node thave ' prev and next links respectively refer to and qand then have ' next link refer to tand have ' prev link refer to likewiseto remove an element stored at node twe can access the nodes and on either side of (and these nodes must existsince we are using sentinelsto remove node between nodes and qwe simply have and point to each other instead of we need not change any of the fields in tfor now can be reclaimed by the garbage collectorsince no one is pointing to table shows the running times of methods for deque implemented with doubly linked list note that every method runs in ( time table performance of deque realized by doubly linked list method time sizeisempty ( getfirstgetlast ( add firstaddlast ( removefirstremovelast (
20,941
in constant time we leave the details of implementing the deque adt efficiently in java as an exercise ( - incidentallyall of the methods of the deque adtas described aboveare included in the java util linkedlist class soif we need to use deque and would rather not implement one from scratchwe can simply use the built-in java util linkedlist class in any casewe show deque interface in code fragment and an implementation of this interface in code fragment code fragment interface deque documented with comments in javadoc style (section note also the use of the generic parameterized typeewhich implies that deque can contain elements of any specified class
20,942
class nodedeque implementing the deque interfaceexcept that we have not shown the class dlnodewhich is generic doubly linked list nodenor have we shown methods getlastaddlastand removefirst
20,943
exercises for source code and help with exercisesplease visit java datastructures net reinforcement - suppose an initially empty stack has performed total of push operations top operationsand pop operations of which generated stackemptyexceptionswhich were caught and ignored what is the current size of sr- if we implemented the stack from the previous problem with an arrayas described in this then what is the current value of the top instance variabler- describe the output of the following series of stack operationspush( )push( )pop()push( )push( )pop()pop()push( )push( )pop()push( )push( )pop()pop()push( )pop()pop( - give recursive method for removing all the elements in stack - give precise and complete definition of the concept of matching for grouping symbols in an arithmetic expression - describe the output for the following sequence of queue operationsenqueue( )enqueue( )dequeue()enqueue( )enqueue( )dequeue()dequeue()enqueue( )enqueue( )dequeue()enqueue( )enqueue( )dequeue()dequeue()enqueue( )dequeue()dequeue( -
20,944
operations front operationsand dequeue operations of which generated queueemptyexceptionswhich were caught and ignored what is the current size of qr- if the queue of the previous problem was implemented with an array of capacity as described in the and it never generated fullqueueexceptionwhat would be the current values of and rr- describe the output for the following sequence of deque adt operationsaddfirst( )addlast( )addlast( )addfirst( )removefirst()remove-last()first()addlast( )removefirst()last()removelast( - suppose you have deque containing the numbers ( , , , , , , , )in this order suppose further that you have an initially empty queue give pseudocode description of method that uses only and (and no other variables or objectsand results in storing the elements ( , , , , , , , )in this order - repeat the previous problem using the deque and an initially empty stack creativity - suppose you have stack containing elements and queue that is initially empty describe how you can use to scan to see if it contains certain element xwith the additional constraint that your algorithm must return the elements back to in their original order you may not use an array or linked list--only and and constant number of reference variables - give pseudo-code description for an array-based implementation of the double-ended queue adt what is the running time for each operationc-
20,945
in random order write shortstraightline piece of pseudo-code (with no loops or recursionthat uses only one comparison and only one variable xyet guarantees with probability / that at the end of this code the variable will store the largest of alice' three integers argue why your method is correct - describe how to implement the stack adt using two queues what is the running time of the push(and pop(methods in this casec- show how to use stack and queue to generate all possible subsets of an -element set nonrecursively - suppose we have an two-dimensional array that we want to use to store integersbut we don' want to spend the ( work to initialize it to all ' (the way java does)because we know in advance that we are only going to use up to of these cells in our algorithmwhich itself runs in (ntime (not counting the time to initialize ashow how to use an array-based stack storing (ijkinteger triples to allow us to use the array without initializing it and still implement our algorithm in (ntimeeven though the initial values in the cells of might be total garbage - describe nonrecursive algorithm for enumerating all permutations of the numbers { , ,nc- postfix notation is an unambiguous way of writing an arithmetic expression without parentheses it is defined so that if "(exp )op(exp )is normal fully parenthesized expression whose operation is opthen the postfix version of this is "pexp pexp op"where pexp is the postfix version of exp and pexp is the postfix version of exp the postfix version of single number or variable is just that number or variable sofor examplethe postfix version of "(( ( ))/ is " /describe nonrecursive way of evaluating an expression in postfix notation - suppose you have two nonempty stacks and and deque describe how to use so that stores all the elements of below all of its original elementswith both sets of elements still in their original order
20,946
alice has three array-based stacksaband csuch that has capacity has capacity and has capacity initiallya is fulland and are empty unfortunatelythe person who programmed the class for these stacks made the push and pop methods private the only method alice can use is static methodtransfer( , )which transfers (by itera-tively applying the private pop and push methodselements from stack to stack until either becomes empty or becomes full sofor examplestarting from our initial configuration and performing transfer(acresults in now holding elements and holding describe sequence of transfer operations that starts from the initial configuration and results in holding elements at the end - alice has two queuess and twhich can store integers bob gives alice odd integers and even integers and insists that she stores all integers in and they then play game where bob picks or at random and then applies the round-robin schedulerdescribed in the to the chosen queue random number of times if the number left out of the queue at the end of this game is oddbob wins otherwisealice wins how can alice allocate integers to queues to optimize her chances of winningwhat is her chance of winningc- suppose bob has four cows that he wants to take across bridgebut only one yokewhich can hold up to two cowsside by sidetied to the yoke the yoke is too heavy for him to carry across the bridgebut he can tie (and untiecows to it in no time at all of his four cowsmazie can cross the bridge in minutesdaisy can cross it in minutescrazy can cross it in minutesand lazy can cross it in minutes of coursewhen two cows are tied to the yokethey must go at the speed of the slower cow describe how bob can get all his cows across the bridge in minutes projects - implement the stack adt with doubly linked list - implement the stack adt using the java arraylist class (without using the built-in java stack classp-
20,947
exercise - and output its value - implement the queue adt using an array - implement the entire queue adt using singly linked list - design an adt for two-colordouble-stack adt that consists of two stacks-one "redand one "blue"--and has as its operations color-coded versions of the regular stack adt operations for examplethis adt should allow for both red push operation and blue push operation give an efficient implementation of this adt using single array whose capacity is set at some value that is assumed to always be larger than the sizes of the red and blue stacks combined - implement the deque adt with doubly linked list - implement the deque adt with an array used in circular fashion - implement the stack and queue interfaces with unique class that extends class nodedeque (code fragment - when share of common stock of some company is soldthe capital gain (orsometimeslossis the difference between the share' selling price and the price originally paid to buy it this rule is easy to understand for single sharebut if we sell multiple shares of stock bought over long period of timethen we must identify the shares actually being sold standard accounting principle for identifying which shares of stock were sold in such case is to use fifo protocol--the shares sold are the ones that have been held the longest (indeedthis is the default method built into several personal finance software packagesfor examplesuppose we buy shares at $ each on day shares at $ on day shares at $ on day and then sell shares on day at $ each then applying the fifo protocol means that of the shares sold were bought on day were bought on day and were bought on day the capital gain in this case would therefore be (- )or
20,948
"buy xshare(sat $ eachor "sell share(sat $ each,assuming that the transactions occur on consecutive days and the values and are integers given this input sequencethe output should be the total capital gain (or lossfor the entire sequenceusing the fifo protocol to identify shares notes we were introduced to the approach of defining data structures first in terms of their adts and then in terms of concrete implementations by the classic books by ahohopcroftand ullman [ ]which incidentally is where we first saw aproblem similar to exercise - exercises - - and - are similar to interview questions said to be from well-known software company for further study of abstract data typessee liskov and guttag [ ]cardelli and wegner [ ]or demurjian [ lists and iterators contents array lists the array list abstract data type the adapter pattern
20,949
simple array-based implementation simple interface and the java util arraylist class implementing an array list using extendable arrays node lists node-based operations positions the node list abstract data type doubly linked list implementation
20,950
iterators the iterator and iterable abstract data types the java for-each loop implementing iterators list iterators in java list adts and the collections framework the java collections framework the java util linkedlist class
20,951
case studythe move-to-front heuristic using sorted list and nested class using list with the move-to-front heuristic possible uses of favorites list exercises java datastructures net array lists suppose we have collection of elements stored in certain linear orderso that we can refer to the elements in as firstsecondthirdand so on such collection is generically referred to as list or sequence we can uniquely refer to each element in using an integer in the range [ , that is equal to the number of elements of that precede in the index of an element in is the number of elements that are before in hencethe first element in has index and the last element has index alsoif an element of has index iits previous element (if it existshas index and its next element (if it existshas index this concept of index is related
20,952
than its indexso the first element is at rank the second is at rank and so on sequence that supports access to its elements by their indices is called an array list (or vectorusing an older termsince our index definition is more consistent with the way arrays are indexed in java and other programming languages (such as and ++)we will be referring to the place where an element is stored in an array list as its "index,not its "rank(although we may use to denote this indexif the letter "iis being used as for-loop counterthis index concept is simple yet powerful notionsince it can be used to specify where to insert new element into list or where to remove an old element the array list abstract data type as an adtan array list has the following methods (besides the standard size(and isempty(methods)get( )return the element of with index ian error condition occurs if size( set(ie)replace with and return the element at index ian error condition occurs if size( add(ie)insert new element into to have index ian error condition occurs if size(remove( )remove from the element at index ian error condition occurs if size( we do not insist that an array should be used to implement an array listso that the element at index is stored at index in the arrayalthough that is one (very naturalpossibility the index definition offers us way to refer to the "placewhere an element is stored in sequence without having to worry about the exact implementation of that sequence the index of an element may change whenever the sequence is updatedhoweveras we illustrate in the following example example we show below some operations on an initially empty array list operation output add( ,
20,953
add( , ( , get( ( , add( , ( , , get( "error( , , remove( ( , add( , ( , , add( , ( , , , add( ,
20,954
get( ( , , , , set( , ( , , , , the adapter pattern classes are often written to provide similar functionality to other classes the adapter design pattern applies to any context where we want to modify an existing class so that its methods match those of relatedbut differentclass or interface one general way for applying the adapter pattern is to define the new class in such way that it contains an instance of the old class as hidden fieldand implement each method of the new class using methods of this hidden instance variable the result of applying the adapter pattern is that new class that performs almost the same functions as previous classbut in more convenient wayhas been created with respect to our discussion of the array list adtwe note that this adt is sufficient to define an adapter class for the deque adtas shown in table (see also exercise - table array list realization of deque by means of an deque method realization with array-list methods size()isempty(size()isempty(getfirst(get( getlast(
20,955
addfirst(eadd( ,eaddlast(eadd(size(),eremovefirst(remove( removelast(remove(size( simple array-based implementation an obvious choice for implementing the array list adt is to use an array awhere [istores ( reference tothe element with index we choose the size of array sufficiently largeand we maintain the number of elements in an instance variablen the details of this implementation of the array list adt are simple to implement the get(ioperationfor examplewe just return [iimplementations of methods add(ieand remove(iare given in code fragment an important (and time-consumingpart of this implementation involves the shifting of elements up or down to keep the occupied cells in the array contiguous these shifting operations are required to maintain our rule of always storing an element whose list index is at index in the array (see figure and also exercise code fragment methods add(ieand remove(iin the array implementation of the array list adt we denotewith nthe instance variable storing the number of elements in the array list
20,956
array-based implementation of an array list that is storing elements(ashifting up for an insertion at index ( )shifting down for removal at index the performance of simple array-based implementation table shows the worst-case running times of the methods of an array list with elements realized by means of an array methods isemptysizeget and set clearly run in ( timebut the insertion and removal methods can take much longer than this in particularadd(ieruns in time (nindeedthe worst case for this operation occurs when since all the existing elements
20,957
which runs in (ntimebecause we have to shift backward elements in the worst case ( in factassuming that each possible index is equally likely to be passed as an argument to these operationstheir average running time is ( )for we will have to shift / elements on average table performance of an array list with elements realized by an array the space usage is ( )where is the size of the array method time size( ( isempty( ( get(io( set(ieo( add(ieo(nremove(io(nlooking more closely at add(ieand remove( )we note that they each run in time ( )for only those elements at index and higher have to be shifted up or down thusinserting or removing an item at the end of an array listusing the methods add(neand remove( )respectively take ( time each moreoverthis observation has an interesting consequence for the adaptation of the array list adt to the deque adt given in section if the array list adt in this case is implemented by means of an array as described abovethen methods addlast and removelast of the deque each run in (
20,958
in (ntime actuallywith little effortwe can produce an array-based implementation of the array list adt that achieves ( time for insertions and removals at index as well as insertions and removals at the end of the array list achieving this requires that we give up on our rule that an element at index is stored in the array at index ihoweveras we would have to use circular array approach like the one we used in section to implement queue we leave the details of this implementation for an exercise ( - simple interface and the java util arraylist class to prepare for constructing java implementation of the array list adtwe showin code fragment java interfaceindexlistthat captures the main methods from the array list adt in this casewe use indexoutofboundsexception to signal an invalid index argument code fragment the array list adt the indexlist interface for the java util arraylist class java provides classjava util arraylistthat implements all the methods that we give above for our array list adt that isit includes all of the methods included in code fragment for the indexlist interface
20,959
of our simplified array list adt for examplethe class java util arraylist also includes methodclear()which removes all the elements from the array listand methodtoarray()which returns an array containing all the elements of the array list in the same order in additionthe class java util arraylist also has methods for searching the listincluding method indexof( )which returns the index of the first occurrence of an element equal to in the array listand method lastindexof( )which returns the index of the last occurrence of an element equal to in the array list both of these methods return the (invalidindex value if an element equal to is not found implementing an array list using extendable arrays in addition to implementing the methods of the indexlist interface (and some other useful methods)the class java util arraylist provides an an interesting feature that overcomes weakness in the simple array implementation specificallya major weakness of the simple array implementation for the array list adt given in section is that it requires advance specification of fixed capacitynfor the total number of elements that may be stored in the array list if the actual number of elementsnof the array list is much smaller than nthen this implementation will waste space worseif increases past nthen this implementation will crash insteadthe java util arraylist uses an interesting extendable-array technique so that we never have to worry about array overflows when using this class as with the java util arraylist classlet us provide means to grow the array that stores the elements of an array list of coursein java (and other programming languages)we cannot actually grow the array aits capacity is fixed at some number nas we have already observed insteadwhen an overflow occursthat iswhen and we make call to the method addwe perform the following additional steps allocate new array of capacity let [ ] [ ]for let bthat iswe use as the array supporting insert the new element in
20,960
viewed as extending the end of the underlying array to make room for more elements (see figure intuitivelythis strategy is much like that of the hermit crabwhich moves into larger shell when it outgrows its previous one figure an illustration of the three steps for "growingan extendable array(acreate new array (bcopy elements from to (creassign reference to the new array not shown is the future garbage collection of the old array implementing the indexlist interface with an extendable array we give portions of java implementation of the array list adt using an extendable array in code fragment this class only provides means for the array to grow exercise - explores an implementation that can also shrink code fragment portions of class arrayindexlist realizing the array list adt by means of an extendable array method checkindex(rn(not shownchecks whether an index is in the range [
20,961
this array replacement strategy might at first seem slowfor performing single array replacement required by some element insertion can take (ntime still
20,962
new elements to the array list before the array must be replaced again this simple fact allows us to show that performing series of operations on an initially empty array list is actually quite efficient as shorthand notationlet us refer to the insertion of an element to be the last element in an array list as push operation (see figure figure running times of series of push operations on java util arraylist of initial size using an algorithmic design pattern called amortizationwe can show that performing sequence of such push operations on an array list implemented with an extendable array is actually quite efficient to perform an amortized analysiswe use an accounting technique where we view the computer as coin-operated appliance that requires the payment of one cyber-dollar for constant amount of computing time when an operation is executedwe should have enough cyberdollars available in our current "bank accountto pay for that operation' running time thusthe total amount of cyber-dollars spent for any computation will be proportional to the total time spent on that computation the beauty of using this analysis method is that we can overcharge some operations in order to save up cyber-dollars to pay for others
20,963
extendable array with initial length one the total time to perform series of push operations in sstarting from being empty is (njustificationlet us assume that one cyber-dollar is enough to pay for the execution of each push operation in sexcluding the time spent for growing the array alsolet us assume that growing the array from size to size requires cyber-dollars for the time spent copying the elements we shall charge each push operation three cyber-dollars thuswe overcharge each push operation that does not cause an overflow by two cyber-dollars think of the two cyber-dollars profited in an insertion that does not grow the array as being "storedat the element inserted an overflow occurs when the array list has elementsfor some integer > and the size of the array used by the array list representing is thusdoubling the size of the array will require cyber-dollars fortunatelythese cyber-dollars can be found at the elements stored in cells - through (see figure note that the previous overflow occurred when the number of elements became larger than - for the first timeand thus the cyber-dollars stored in cells - through were not previously spent thereforewe have valid amortization scheme in which each operation is charged three cyber-dollars and all the computing time is paid for that iswe can pay for the execution of push operations using cyber-dollars in other wordsthe amortized running time of each push operation is ( )hencethe total running time of push operations is (nfigure illustration of series of push operations on an array list(aan -cell array is fullwith two cyber-dollars "storedat cells through (ba push operation causes an overflow and doubling of capacity copying the eight old elements to the new array is paid for by the cyber-dollars already stored in the table inserting the new element is paid for by one of the cyber-dollars charged to the push operationand the two cyber-dollars profited are stored at cell
20,964
node lists using an index is not the only means of referring to the place where an element appears in sequence if we have sequence implemented with (singly or doublylinked listthen it could possibly be more natural and efficient to use node instead of an index as means of identifying where to access and update in this sectionwe define the node list adtwhich abstracts the concrete linked list data structure (sections and using related position adt that abstracts the notion of "placein node list node-based operations let be (singly or doublylinked list we would like to define methods for that take nodes as parameters and provide nodes as return types such methods could provide significant speedups over index-based methodsbecause finding the index of an element in linked list requires searching through the list incrementally from its beginning or endcounting elements as we go for instancewe could define hypothetical method remove(vthat removes the element of stored at node of the list using node as parameter allows us to remove an element in ( time by simply going directly to the place where that node is stored and then "linking outthis node through an update of the next and prev links of its neighbors similarlywe could insertin ( timea new element into with an operation such as addafter(ve)which specifies the node after which the node of the new element should be inserted in this casewe simply "link inthe new node defining methods of list adt by adding such node-based operations raises the issue of how much information we should be exposing about the implementation of our list certainlyit is desirable for us to be able to use either singly or doubly
20,965
user to modify the internal structure of list without our knowledge such modification would be possiblehoweverif we provided reference to node in our list in form that allowed the user to access internal data in that node (such as next or prev fieldto abstract and unify the different ways of storing elements in the various implementations of listwe introduce the concept of positionwhich formalizes the intuitive notion of "placeof an element relative to others in the list positions so as to safely expand the set of operations for listswe abstract notion of "positionthat allows us to enjoy the efficiency of doubly or singly linked list implementations without violating object-oriented design principles in this frameworkwe view list as collection of elements that stores each element at position and that keeps these positions arranged in linear order position is itself an abstract data type that supports the following simple methodelement()return the element stored at this position position is always defined relativelythat isin terms of its neighbors in lista position will always be "aftersome position and "beforesome position (unless is the first or last positiona position pwhich is associated with some element in list sdoes not changeeven if the index of changes in sunless we explicitly remove (andhencedestroy position pmoreoverthe position does not change even if we replace or swap the element stored at with another element these facts about positions allow us to define set of position-based list methods that take position objects as parameters and also provide position objects as return values the node list abstract data type using the concept of position to encapsulate the idea of "nodein listwe can define another type of sequence adt called the node list adt this adt supports the following methods for list sfirst()return the position of the first element of san error occurs if is empty last()return the position of the last element of san error occurs if is empty prev( )
20,966
error occurs if is the first position next( )return the position of the element of following the one at position pan error occurs if is the last position the above methods allow us to refer to relative positions in liststarting at the beginning or endand to move incrementally up or down the list these positions can intuitively be thought of as nodes in the listbut note that there are no specific references to node objects moreoverif we provide position as an argument to list methodthen that position must represent valid position in that list node list update methods in addition to the above methods and the generic methods size and isemptywe also include the following update methods for the node list adtwhich take position objects as parameters and/or provide position objects as return values set(pe)replace the element at position with ereturning the element formerly at position addfirst( )insert new element into as the first element addlast( )insert new element into as the last element addbefore(pe)insert new element into before position addafter(pe)insert new element into after position remove( )remove and return the element at position in sinvalidating this position in
20,967
their placeswithout worrying about the exact way those places are represented (see figure figure node list the positions in the current order are pqrand there may at first seem to be redundancy in the above repertory of operations for the node list adtsince we can perform operation addfirst(ewith addbefore(first() )and operation addlast(ewith addafter(getlast()ebut these substitutions can only be done for nonempty list note that an error condition occurs if position passed as argument to one of the list operations is invalid reasons for position to be invalid includep null was previously deleted from the list is position of different list is the first position of the list and we call prev(pp is the last position of the list and we call next(pwe illustrate the operations of the node list adt in the following example example we show below series of operations for an initially empty list node we use variables and so onto denote different positionsand we show the object currently stored at such position in parentheses operation output addfirst(
20,968
first( ( ( addafter( , ( , next( ( ( , addbefore( , ( , , prev( ( ( , , addfirst( ( , , , last( ( ( , , , remove(first()
20,969
set( , ( , , addafter(first(), ( , , , the node list adtwith its built-in notion of positionis useful in number of settings for examplea program that simulates game of cards could model each person' hand as node list since most people keep cards of the same suit togetherinserting and removing cards from person' hand could be implemented using the methods of the node list adtwith the positions being determined by natural ordering of the suits likewisea simple text editor embeds the notion of positional insertion and removalsince such editors typically perform all updates relative to cursorwhich represents the current position in the list of characters of text being edited java interface representing the position adt is given in code fragment code fragment adt java interface for the position an interface for the node list adtcalled position listis given in code fragment this interface uses the following exceptions to indicate error conditions boundaryviolationexceptionthrown if an attempt is made at accessing an element whose position is outside the range of positions of the list (for examplecalling method next on the last position of the sequenceinvalid position exceptionthrown if position provided as argument is not valid (for exampleit is null reference or it has no associated list
20,970
adt java interface for the node list yet another deque adapter with respect to our discussion of the node list adtwe note that this adt is sufficient to define an adapter class for the deque adtas shown in table table node list realization of deque by means of
20,971
realization with node-list methods size()isempty(size()isempty(getfirst(first()*element(getlast(last()*element(addfirst(eaddfirst(eaddlast(eaddlast(eremovefirst(remove(first()removelast(remove(last()doubly linked list implementation suppose we would like to implement the node list adt using doubly linked list (section we can simply make the nodes of the linked list implement the position adt that iswe have each node implement the position interface and therefore define methodelement()which returns the element stored at the node thusthe nodes themselves act as positions they are viewed internally by the linked list as nodesbut from the outsidethey are viewed only as positions in the internal viewwe can give each node instance variables prev and next that respectively refer to the predecessor and successor nodes of (which could in fact be header or trailer sentinel nodes marking the beginning and end of the listinstead of using variables prev and next directlywe define methods getprevsetprevgetnextand setnext of node to access and modify these variables
20,972
linked list implementing the position adt this class is similar to class dnode shown in code fragment except that now our nodes store generic element instead of character string note that the prev and next instance variables in the dnode class below are private references to other dnode objects code fragment class dnode realizing node of doubly linked list and implementing the position interface (adtgiven position in swe can "unwrapp to reveal the underlying node this is accomplished by casting the position to node once we have node vwe canfor exampleimplement method prev(pwith getprev (unless the node returned by getprev is the headerin which case we signal an errorthereforepositions in doubly linked list implementation can be supported in an object-oriented way without any additional time or space overhead consider how we might implement the addafter(pemethodfor inserting an element after position similar to the discussion in section we create
20,973
next and prev references of ' two new neighbors this method is given in code fragment and is illustrated (againin figure recalling the use of sentinels (section )note that this algorithm works even if is the last real position code fragment inserting an element after position in linked list figure adding anew node after the position for "jfk"(abefore the insertion(bcreating node with element "bwiand linking it in(cafter the insertion the algorithms for methods addbeforeaddfirstand addlast are similar to that for method addafter we leave their details as an exercise ( -
20,974
position similar to the discussion in section to perform this operationwe link the two neighbors of to refer to one another as new neighbors--linking out note that after is linked outno nodes will be pointing to phencethe garbage collector can reclaim the space for this algorithm is given in code fragment and is illustrated in figure recalling our use of header and trailer sentinelsnote that this algorithm works even if is the firstlastor only real position in the list code fragment removing an element stored at position in linked list figure removing the object stored at the position for "pvd"(abefore the removal(blinking out the old node(cafter the removal (and garbage collection
20,975
adt in ( time thusa doubly linked list is an efficient implementation of the list adt node list implementation in java portions of the java class nodepositionlistwhich implements the node list adt using doubly linked listare shown in code fragments code fragment shows nodeposition list' instance variablesits constructorand methodcheckpositionwhich performs safety checks and "unwrapsa positioncasting it back to dnode code fragment shows additional accessor and update methods code fragment shows additional update methods code fragment portions of the nodepositionlist class implementing the node list adt with doubly linked list (continues in code fragments and
20,976
nodepositionlist class implementing the node list adt with doubly linked list (continued from code fragment continues in code fragment
20,977
nodepositionlist class implementing the node list adt with doubly linked list (continued from code fragments and note that the mechanism used to invalidate position in the remove method is
20,978
checkposition convenience function iterators typical computation on an array listlistor sequence is to march through its elements in orderone at timefor exampleto look for specific element the iterator and iterable abstract data types
20,979
through collection of elements one element at time an iterator consists of sequence sa current element in sand way of stepping to the next element in and making it the current element thusan iterator extends the concept of the position adt we introduced in section in facta position can be thought of as an iterator that doesn' go anywhere an iterator encapsulates the concepts of "placeand "nextin collection of objects we define the iterator adt as supporting the following two methodshasnext()test whether there are elements left in the iterator next()return the next element in the iterator note that the iterator adt has the notion of the "currentelement in traversal of sequence the first element in an iterator is returned by the first call to the method nextassuming of course that the iterator contains at least one element an iterator provides unified scheme to access all the elements of collection of objects in way that is independent from the specific organization of the collection an iterator for an array listlistor sequence should return the elements according to their linear ordering simple iterators in java java provides an iterator through its java util iterator interface we note that the java util scanner class (section implements this interface this interface supports an additional (optionalmethod to remove the previously returned element from the collection this functionality (removing elements through an iteratoris somewhat controversial from an object-oriented viewpointhoweverand it is not surprising that its implementation by classes is optional incidentallyjava also provides the java util enumeration interfacewhich is historically older than the iterator interface and uses names hasmoreelements(and nextelement(the iterable abstract data type in order to provide unified generic mechanism for scanning through data structureadts storing collections of objects should support the following methoditerator()return an iterator of the elements in the collection this method is supported by the java util arraylist class in factthis method is so importantthat there is whole interface
20,980
make it simple for us to specify computations that need to loop through the elements of list to guarantee that node list supports the above methodsfor examplewe could add this method to the position list interfaceas shown in code fragment in this casewe would also want to state that position list extends iterable thereforelet us assume that our array lists and node lists lists support the iterator(method code fragment adding the iterator method to the position list interface given such position list definitionwe could use an iterator returned by the iterator(method to create string representation of node listas shown in code fragment code fragment example of java iterator used to convert node list to string the java for-each loop
20,981
constructjava provides shorthand notation for such loopscalled the for-each loop the syntax for such loop is as followsfor (type name expressionloop statement where expression evaluates to collection that implements the java lang iterable interfacetype is the type of object returned by the iterator for this classand name is the name of variable that will take on the values of elements from this iterator in the loop_statement this notation is really just shorthand for the followingfor (iterator it expression iterator()it hasnext()type name it next()loop_statement for exampleif we had listvaluesof integer objectsand values implements java lang iterablethen we can add up all the integers in values as followslist values/statements that create new values list and fill it with integers int sum for (integer valuessum + /unboxing allows this we would read the above loop as"for each integer in valuesdo the loop body (in this caseadd to sumin addition to the above form of for-each loopjava also allows for-each loop to be defined for the case when expression is an array of type typewhichin this casecan be either base type or an object type for examplewe can total up the integers in an arrayvwhich stores the first ten positive integersas followsint[ { }
20,982
for (int vtotal +iimplementing iterators one way to implement an iterator for collection of elements is to make "snapshotof it and iterate over that this approach would involve storing the collection in separate data structure that supports sequential access to its elements for examplewe could insert all the elements of the collection into queuein which case method hasnext(would correspond to !isempty(and next(would correspond to enqueue(with this approachthe method iterator(takes (ntime for collection of size since this copying overhead is relatively costlywe preferin most casesto have iterators operate on the collection itselfnot copy in implementing this direct approachwe need only to keep track of where in the collection the iterator' cursor points thuscreating new iterator in this case simply involves creating an iterator object that represents cursor placed just before the first element of the collection likewiseperforming the next(method involves returning the next elementif it existsand moving the cursor just past this element' position thusin this approachcreating an iterator takes ( timeas do each of the iterator' methods we show class implementing such an iterator in code fragment and we show in code fragment how this iterator could be used to implement the iterator(method in the nodepositionlist class code fragment position list an element iterator class for
20,983
the iterator(method of class nodepositionlist position iterators for adts that support the notion of positionsuch as the list and sequence adtswe can also provide the following methodpositions()return an iterable object (like an array list or node listcontaining the positions in the collection as elements an iterator returned by this method allows us to loop through the positions of list to guarantee that node list supports this methodwe could add it to the positionlist interfaceas shown in code fragment then we couldfor exampleadd an implementation of this method to the nodepositionlistas shown in code fragment this method uses the nodepositionlist class itself to create list that contains the positions of the original list as its elements returning this list of positions as our iterable object allows us to
20,984
original list code fragment adding iterator methods to the position list interface code fragment the positions(method of class nodepositionlist the iterator(method returned by this and other iterable objects defines restricted type of iterator that allows only one pass through the elements more powerful iterators can also be definedhoweverwhich allows us to move forward and backward over certain ordering of the elements list iterators in java the java util linked list class does not expose position concept to users in its api insteadthe preferred way to access and update linkedlist object in javawithout using indicesis to use listiterator that is generated by the linked listusing listiterator(method such an iterator provides forward and backward traversal methods as well as local update methods it views its current position as being before the first elementbetween two elementsor after
20,985
being located between two characters on screen specificallythe java util listiterator interface includes the following methodsadd( )add the element at the current position of the iterator hasnext()true if and only if there is an element after the current position of the iterator hasprevious()true if and only if there is an element before the current position of the iterator previous()return the element before the current position and sets the current position to be before next()return the element after the current position and sets the current position to be after nextindex()return the index of the next element previousindex()return the index of the previous element set( )replace the element returned by the previous next or previous operation with remove()remove the element returned by the previous next or previous operation it is risky to use multiple iterators over the same list while modifying its contents if insertionsdeletionsor replacements are required at multiple "placesin listit is safer to use positions to specify these locations but the java util linkedlist class does not expose its position objects to the user
20,986
to its iterator(method)java util iterator objects have "fail-fastfeature that immediately invalidates such an iterator if its underlying collection is modified unexpectedly for exampleif java util linkedlist object has returned five different iterators and one of them modifies lthen the other four all become immediately invalid that isjava allows many list iterators to be traversing linked list at the same timebut if one of them modifies (using an addsetor remove method)then all the other iterators for become invalid likewiseif is modified by one of its own update methodsthen all existing iterators for immediately become invalid the java util list interface and its implementations java provides functionality similar to our array list and node lists adt in the java util list interfacewhich is implemented with an array in java util arraylist and with linked list in java util linkedlist there are some trade-offs between these two implementationswhich we explore in more detail in the next section moreoverjava uses iterators to achieve functionality similar to what our node list adt derives from positions table shows corresponding methods between our (array and nodelist adts and the java util interfaces list and listiterator interfaceswith notes about their implementations in the java util classes arraylist and linkedlist table correspondences between methods in the array list and node list adts and the java util interfaces list and listiterator we use and as abbreviations for java util arraylist and java util linked list (or their running timeslist adt method java util list method listiterator method notes size(size( ( time
20,987
isempty( ( time get(iget(ia is ( ) is (min{in }first(listiterator(first element is next last(listiterator(size()last element is previous prev(pprevious( ( time next(pnext( ( time set(peset(eo( time set( ,eset(iea is ( ) is (min{ , }add( ,
20,988
(ntime remove(iremove(ia is ( ) is (min{in }addfirst(eadd( ,ea is ( ), is ( addfirst(eaddfirst(eonly exists in lo( addlast(eadd(eo( time addlast(eaddlast(eonly exists in lo( addafter(peadd(einsertion is at cursora is ( ) is ( addbefore( ,eadd(einsertion is at cursora is ( ), is ( remove(premove(
20,989
list adts and the collections framework in this sectionwe discuss general list adtswhich combine methods of the dequearray listand/or node list adts before describing such adtswe mention larger context in which they exist the java collections framework java provides package of data structure interfaces and classeswhich together define the java collections framework this packagejava utilincludes versions of several of the data structures discussed in this booksome of which we have already discussed and others of which we discuss in the remainder of this book in particularthe java util package includes the following interfacescollectiona general interface for any data structure that contains collection of elements it extends java lang iterablehenceit includes an iterator(methodwhich returns an iterator of the elements in this collection iteratoran interface for the simple iterator adt listan interface extending collection to include the array list adt it also includes method listiterator for returning listiterator object for this list listiteratoran iterator interface that provides both forward and backward traversal over listas well as cursor-based update methods mapan interface for mapping keys to values this concept and interface are discussed in section queue
20,990
include peek((same as front())offer( (same as enqueue( ))and poll((same as dequeue()setan interface extending collection to sets the java collections framework also includes several concrete classes implementing various combinations of the above interfaces rather than list each of these classes herehoweverwe discuss them at more appropriate places in this book one topic we would like to stress nowhoweveris that any class implementing the java util collection interface also implements the java lang iterable interfacehenceit includes an iterator(method and can be used in for-each loop in additionany class implementing the java util list interface also includes listiterator(methodas well as we observed abovesuch interfaces are useful for looping through the elements of collection or list the java util linkedlist class the java util linked list class contains lot of methodsincluding all of the methods of the deque adt (section and all of the methods from the array list adt (section in additionas we mentioned aboveit also provides functionality similar to that of the node list adt through the use of its list iterator performance of the java util linkedlist class the documentation for the java util linkedlist class makes it clear that this class is implemented with doubly linked list thusall of the update methods of the associated list iterator run in ( time each likewiseall of the methods of the deque adt also run in ( time eachsince they merely involve updating or querying the list at its ends but the methods from the array list adt are also included in the java util linkedlistwhich arein generalnot well-suited to an implementation of doubly linked list in particularsince linked list does not allow for indexed access to its elementsperforming the operation get( )to return the element at given index irequires that we perform link "hoppingfrom one of the ends of the listcounting up or downuntil we locate the node storing the element with index as slight optimizationwe observe that we can start this hopping from the closer end of the listthus achieving running time that is (min( ))
20,991
search occurs when rn/ thusthe running time is still (noperations add( ,eand remove(ialso must perform link hopping to locate the node storing the element with index iand then insert or delete node the running times of these implementations of add( ,eand remove(iare likewise (min( - + ))which is (none advantage of this approach is thatif or as is the case in the adaptation of the array list adt to the deque adt given in section then add and remove run in ( time butin generalusing array-list methods with java util linkedlist object is inefficient sequences sequence is an adt that supports all of the methods of the deque adt (section )the array list adt (section )and the node list adt (section that isit provides explicit access to the elements in the list either by their indices or by their positions moreoversince it provides this dual access capabilitywe also includein the sequence adtthe following two "bridgingmethods that provide connections between indices and positionsatindex( )return the position of the element with index ian error condition occurs if size( indexof( )return the index of the element at position multiple inheritance in the sequence adt the definition of the sequence adt as including all the methods from three different adts is an example of multiple inheritance (section that isthe sequence adt inherits methods from three "superabstract data types in other wordsits methods include the union of the methods of these super adts see code fragment for java specification of the sequence adt as java interface code fragment the sequence interface defined via multiple inheritance it includes all the methods of the dequeindexlistand
20,992
type )and adds two more methods implementing sequence with an array if we implement the sequence adt with doubly linked listwe would get similar performance to that of the java util linkedlist class so suppose instead we want to implement sequence by storing each element of in cell [iof an array we can define position object to hold an index and reference to array aas instance variablesin this case we can then implement method element(psimply by returning [ia major drawback with this approachhoweveris that the cells in have no way to reference their corresponding positions thusafter performing an add first operationwe have no way of informing the existing positions in that their indices each went up by (remember that positions in sequence are always defined relative to their neighboring positionsnot their indiceshenceif we are going to implement general sequence with an arraywe need different approach consider an alternate solutionthenin whichinstead of storing the elements of in array awe store new kind of position object in each cell of aand we store elements in positions the new position object holds the index and the element associated with with this data structureillustrated in figure we can easily scan through the array to update the index variable for each position whose index changes because of an insertion or deletion figure an array-based implementation of the sequence adt
20,993
in this array implementation of sequencethe addfirstaddbeforeaddafterand remove methods take (ntimebecause we have to shift position objects to make room for the new position or to fill in the hole created by the removal of the old position (just as in the insert and remove methods based on indexall the other position-based methods take ( time case studythe move-to-front heuristic suppose we would like to maintain collection of elements while keeping track of the number of times each element is accessed keeping such access counts allows us to know which elements are among the "top tenmost popularfor instance examples of such scenarios include web browser that keeps track of the most popular web addresses (or urlsa user visits or photo album program that maintains list of the most popular images user views in additiona favorites list could be used in graphical user interface (guito keep track of the most popular buttons used in pull-down menuand then present the user with condensed pulldowns containing the most popular options thereforein this sectionwe consider how we can implement favorite list adtwhich supports the size(and isempty(methods as well as the followingaccess( )access the element eincrementing its access countand adding it to the favorites list if it is not already present remove( )remove element from the favorites listprovided it is already there
20,994
return an iterable collection of the most accessed elements using sorted list and nested class the first implementation of favorite list that we consider (in code fragments is to build classfavoriteliststoring references to accessed objects in linked list ordered by nonincreasing access counts this class also uses feature of java that allows us to define related class nested inside an enclosing class definition such nested class must be declared staticto indicate that this definition is related to the enclosing classnot any specific instance of that class using nested classes allows us to define "helperor "supportclasses that can be protected from outside use in this casethe nested classentrystoresfor each element in our lista pair ( , )where is the access count for and is value reference to the element itself each time an element is accessedwe find it in the linked list (adding it if it is not already thereand increment its access count removing an element amounts to finding it and taking it out of our linked list returning the most accessed elements simply involves our copying the entry values into an output list according to their order in the internal linked list code fragment class favoriteslist (continues in code fragment
20,995
class favoritelistincluding nested classentryfor representing elements and their access count (continued from code fragment using list with the move-to-front heuristic
20,996
time proportional to the index of in the favorite list that isif is the kth most popular element in the favorite listthen accessing it takes (ktime in many reallife access sequencesincluding those formed by the visits that users make to web pagesit is common thatonce an element is accessedit is likely to be accessed again in the near future such scenarios are said to possess locality of reference heuristicor rule of thumbthat attempts to take advantage of the locality of reference that is present in an access sequence is the move-to-front heuristic to apply this heuristiceach time we access an element we move it all the way to the front of the list our hopeof courseis that this element will then be accessed again in the near future considerfor examplea scenario in which we have elements and the following series of accesseselement is accessed times element is accessed times element is accessed times if we store the elements sorted by their access countsinserting each element the first time it is accessedthen each access to element runs in ( time each access to element runs in ( time each access to element runs in (ntime thusthe total time for performing the series of accesses is proportional to nn* ( +nn( )/ which is ( on the other handif we use the move-to-front heuristicinserting each element the first time it is accessedthen each access to element takes ( time each access to element takes ( time each access to element runs in ( time
20,997
move-to-front implementation has faster access times for this scenario this benefit comes at costhowever implementing the move-to-front heuristic in java in code fragment we give an implementation of favorite list using the move-to-front heuristic we implement the move-to-front approach in this case by defining new classfavoritelistmtfwhich extends the favoritelist class and then overrides the definitions of the moveup and top methods the moveup method in this case simply removes the accessed element from its present position in the linked list and then inserts this element back in this list at the front the top methodon the other handis more complicated the trade-offs with the move-to-front heuristic now that we are no longer maintaining the favorite list as list of entries ordered by their value' access countswhen we are asked to find the most accessed elementswe need to search for them in particularwe can implement method top(kas follows we copy the entries of our favorite list into another listcand we create an empty listt we scan list times in each scanwe find an entry of with the largest access countremove this entry from cand insert its value at the end of we return list this implementation of method top takes (kntime thuswhen is constantmethod top runs in (ntime this occursfor examplewhen we want to get the "top tenlist howeverif is proportional to nthen top runs in ( time this occursfor examplewhen we want "top %list stillthe move-to-front approach is just heuristicor rule of thumbfor there are access sequences where using the move-to-front approach is slower than simply keeping the favorite list ordered by access counts in additionit trades off the potential speed of performing accesses that possess locality of referencefor slower reporting of the top elements possible uses of favorites list in code fragment we use an example application of our favorite list implementations to solve the problem of maintaining the most popular urls in simulated sequence of web page accesses this program accesses set of urls in
20,998
accessed in the simulation code fragment class favoritelistmtf implementing the move-to-front heuristic this class extends favoritelist (code fragments and overrides methods moveup and top
20,999
illustrating the use of the favoriteslist and favoritelistmtf classes for counting web page access counts this simulation randomly