id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
22,700 | linked lists current display()and you've forgotten whether current is link objecta linklist objector something else the constructor initializes the data there' no need to initialize the next field because it' automatically set to null when it' created (howeveryou could set it to null explicitlyfor clarity the null value means it doesn' refer to anythingwhich is the situation until the link is connected to other links we've made the storage type of the link fields (idata and so onpublic if they were privatewe would need to provide public methods to access themwhich would require extra codethus making the listing longer and harder to read ideallyfor security we would probably want to restrict link-object access to methods of the linklist class howeverwithout an inheritance relationship between these classesthat' not very convenient we could use the default access specifier (no keywordto give the data package access (access restricted to classes in the same directory)but that has no effect in these demo programswhich occupy only one directory anyway the public specifier at least makes it clear that this data isn' private in more serious program you would probably want to make all the data fields in the link class private the linklist class the linklist class contains only one data itema reference to the first link on the list this reference is called first it' the only permanent information the list maintains about the location of any of the links it finds the other links by following the chain of references from firstusing each link' next fieldclass linklist private link first/ref to first link on list /public void linklist(/constructor first null/no items on list yet /public boolean isempty(/true if list is empty return (first==null) |
22,701 | //other methods go here the constructor for linklist sets first to null this isn' really necessary becauseas we notedreferences are set to null automatically when they're created howeverthe explicit constructor makes it clear that this is how first begins when first has the value nullwe know there are no items on the list if there were any itemsfirst would contain reference to the first one the isempty(method uses this fact to determine whether the list is empty the insertfirst(method the insertfirst(method of linklist inserts new link at the beginning of the list this is the easiest place to insert link because first already points to the first link to insert the new linkwe need only set the next field in the newly created link to point to the old first link and then change first so it points to the newly created link this situation is shown in figure first next next next next null abefore insertion first next next next next null link next bafter insertion figure inserting new link |
22,702 | linked lists in insertfirst(we begin by creating the new link using the data passed as arguments then we change the link references as we just noted/insert at start of list public void insertfirst(int iddouble dd/make new link link newlink new link(iddd)newlink next first/newlink --old first first newlink/first --newlink the --arrows in the comments in the last two statements mean that link (or the first fieldconnects to the next (downstreamlink (in doubly linked lists we'll see upstream connections as wellsymbolized by <-arrows compare these two statements with figure make sure you understand how the statements cause the links to be changedas shown in the figure this kind of reference manipulation is the heart of linked-list algorithms the deletefirst(method the deletefirst(method is the reverse of insertfirst(it disconnects the first link by rerouting first to point to the second link this second link is found by looking at the next field in the first linkpublic link deletefirst(link temp firstfirst first nextreturn temp/delete first item /(assumes list not empty/save reference to link /delete itfirst-->old next /return deleted link the second statement is all you need to remove the first link from the list we choose to also return the linkfor the convenience of the user of the linked listso we save it in temp before deleting it and return the value of temp figure shows how first is rerouted to delete the object in +and similar languagesyou would need to worry about deleting the link itself after it was disconnected from the list it' in memory somewherebut now nothing refers to it what will become of itin javathe garbage collection process will destroy it at some point in the futureit' not your responsibility notice that the deletefirst(method assumes the list is not empty before calling ityour program should verify this fact with the isempty(method |
22,703 | first null abefore deletion first null bafter deletion figure deleting link the displaylist(method to display the listyou start at first and follow the chain of references from link to link variable current points to (or technically refers toeach link in turn it starts off pointing to firstwhich holds reference to the first link the statement current current nextchanges current to point to the next link because that' what' in the next field in each link here' the entire displaylist(methodpublic void displaylist(system out print("list (first-->last)")link current first/start at beginning of list while(current !null/until end of listcurrent displaylink()/print data current current next/move to next link system out println("")the end of the list is indicated by the next field in the last link pointing to null rather than another link how did this field get to be nullit started that way when the link was created and was never given any other value because it was always at |
22,704 | linked lists the end of the list the while loop uses this condition to terminate itself when it reaches the end of the list figure shows how current steps along the list first next next next next null )before current current next current first next next next next null )after current current next current figure stepping along the list at each linkthe displaylist(method calls the displaylink(method to display the data in the link the linklist java program listing shows the complete linklist java program you've already seen all the components except the main(routine listing the linklist java program /linklist java /demonstrates linked list /to run this programc>java linklistapp ///////////////////////////////////////////////////////////////class link public int idata/data item (keypublic double ddata/data item public link next/next link in list / |
22,705 | listing continued public link(int iddouble dd/constructor idata id/initialize data ddata dd/('nextis automatically /set to null/public void displaylink(/display ourself system out print("{idata "ddata "")/end class link ///////////////////////////////////////////////////////////////class linklist private link first/ref to first link on list /public linklist(/constructor first null/no items on list yet /public boolean isempty(/true if list is empty return (first==null)//insert at start of list public void insertfirst(int iddouble dd/make new link link newlink new link(iddd)newlink next first/newlink --old first first newlink/first --newlink /public link deletefirst(/delete first item /(assumes list not emptylink temp first/save reference to link first first next/delete itfirst-->old next return temp/return deleted link |
22,706 | listing linked lists continued /public void displaylist(system out print("list (first-->last)")link current first/start at beginning of list while(current !null/until end of listcurrent displaylink()/print data current current next/move to next link system out println("")//end class linklist ///////////////////////////////////////////////////////////////class linklistapp public static void main(string[argslinklist thelist new linklist()/make new list thelist insertfirst( )thelist insertfirst( )thelist insertfirst( )thelist insertfirst( )/insert four items thelist displaylist()/display list while!thelist isempty(/until it' emptylink alink thelist deletefirst()/delete link system out print("deleted ")/display it alink displaylink()system out println("")thelist displaylist()/display list /end main(/end class linklistapp /////////////////////////////////////////////////////////////// |
22,707 | in main(we create new listinsert four new links into it with insertfirst()and display it thenin the while loopwe remove the items one by one with deletefirst(until the list is empty the empty list is then displayed here' the output from linklist javalist (first-->last){ { { { deleted { deleted { deleted { deleted { list (first-->last)finding and deleting specified links our next example program adds methods to search linked list for data item with specified key value and to delete an item with specified key value thesealong with insertion at the start of the listare the same operations carried out by the linklist workshop applet the complete linklist java program is shown in listing listing the linklist java program /linklist java /demonstrates linked list /to run this programc>java linklist app ///////////////////////////////////////////////////////////////class link public int idata/data item (keypublic double ddata/data item public link next/next link in list /public link(int iddouble dd/constructor idata idddata dd/public void displaylink(/display ourself system out print("{idata "ddata "")/end class link |
22,708 | listing linked lists continued ///////////////////////////////////////////////////////////////class linklist private link first/ref to first link on list /public linklist(/constructor first null/no links on list yet /public void insertfirst(int iddouble dd/make new link link newlink new link(iddd)newlink next first/it points to old first link first newlink/now first points to this /public link find(int key/find link with given key /(assumes non-empty listlink current first/start at 'firstwhile(current idata !key/while no matchif(current next =null/if end of listreturn null/didn' find it else /not end of listcurrent current next/go to next link return current/found it /public link delete(int key/delete link with given key /(assumes non-empty listlink current first/search for link link previous firstwhile(current idata !keyif(current next =nullreturn null/didn' find it else previous current/go to next link |
22,709 | listing continued current current next/found it if(current =first/if first linkfirst first next/change first else /otherwiseprevious next current next/bypass it return current/public void displaylist(/display the list system out print("list (first-->last)")link current first/start at beginning of list while(current !null/until end of listcurrent displaylink()/print data current current next/move to next link system out println("")//end class linklist ///////////////////////////////////////////////////////////////class linklist app public static void main(string[argslinklist thelist new linklist()/make list thelist insertfirst( )thelist insertfirst( )thelist insertfirst( )thelist insertfirst( )/insert items thelist displaylist()/display list link thelist find( )/find item iff !nullsystem out println("found link with key idata)else |
22,710 | listing linked lists continued system out println("can' find link")link thelist delete( )/delete item ifd !null system out println("deleted link with key idata)else system out println("can' delete link")thelist displaylist()/end main(/end class linklist app /display list ///////////////////////////////////////////////////////////////the main(routine makes listinserts four itemsand displays the resulting list it then searches for the item with key deletes the item with key and displays the list again here' the outputlist (first-->last){ { { { found link with key deleted link with key list (first-->last){ { { the find(method the find(method works much like the displaylist(method in the linklist java program the reference current initially points to first and then steps its way along the links by setting itself repeatedly to current next at each linkfind(checks whether that link' key is the one it' looking for if the key is foundit returns with reference to that link if find(reaches the end of the list without finding the desired linkit returns null the delete(method the delete(method is similar to find(in the way it searches for the link to be deleted howeverit needs to maintain reference not only to the current link (current)but to the link preceding the current link (previousit does so becauseif it deletes the current linkit must connect the preceding link to the following linkas shown in figure the only way to tell where the preceding link is located is to maintain reference to it |
22,711 | first next next next next null abefore deletion previous first current next next next null bafter deletion previous current figure deleting specified link at each cycle through the while loopjust before current is set to current nextprevious is set to current this keeps it pointing at the link preceding current to delete the current link once it' foundthe next field of the previous link is set to the next link special case arises if the current link is the first link because the first link is pointed to by the linklist' first field and not by another link in this case the link is deleted by changing first to point to first nextas we saw in the linklist java program with the deletefirst(method here' the code that covers these two possibilitiesif(current =firstfirst first nextelse previous next current next/found it /if first link/change first /otherwise/bypass link other methods we've seen methods to insert and delete items at the start of listand to find specified item and delete specified item you can imagine other useful list methods for examplean insertafter(method could find link with specified key value and insert new link following it we'll see such method when we talk about list iterators at the end of this |
22,712 | linked lists double-ended lists double-ended list is similar to an ordinary linked listbut it has one additional featurea reference to the last link as well as to the first figure shows such list first next next next next null last figure double-ended list the reference to the last link permits you to insert new link directly at the end of the list as well as at the beginning of courseyou can insert new link at the end of an ordinary single-ended list by iterating through the entire list until you reach the endbut this approach is inefficient access to the end of the list as well as the beginning makes the double-ended list suitable for certain situations that single-ended list can' handle efficiently one such situation is implementing queuewe'll see how this technique works in the next section listing contains the firstlastlist java programwhich demonstrates doubleended list (incidentallydon' confuse the double-ended list with the doubly linked listwhich we'll explore later in this listing the firstlastlist java program /firstlastlist java /demonstrates list with first and last references /to run this programc>java firstlastapp ///////////////////////////////////////////////////////////////class link public long ddata/data item public link next/next link in list /public link(long /constructor ddata /public void displaylink(/display this link system out print(ddata ") |
22,713 | listing continued //end class link ///////////////////////////////////////////////////////////////class firstlastlist private link first/ref to first link private link last/ref to last link /public firstlastlist(/constructor first null/no links on list yet last null/public boolean isempty(/true if no links return first==null/public void insertfirst(long dd/insert at front of list link newlink new link(dd)/make new link ifisempty(/if empty listlast newlink/newlink <-last newlink next first/newlink --old first first newlink/first --newlink /public void insertlast(long dd/insert at end of list link newlink new link(dd)/make new link ifisempty(/if empty listfirst newlink/first --newlink else last next newlink/old last --newlink last newlink/newlink <-last /public long deletefirst(/delete first link /(assumes non-empty listlong temp first ddataif(first next =null/if only one item |
22,714 | listing linked lists continued last null/null <-last first first next/first --old next return temp/public void displaylist(system out print("list (first-->last)")link current first/start at beginning while(current !null/until end of listcurrent displaylink()/print data current current next/move to next link system out println("")//end class firstlastlist ///////////////////////////////////////////////////////////////class firstlastapp public static void main(string[args/make new list firstlastlist thelist new firstlastlist()thelist insertfirst( )thelist insertfirst( )thelist insertfirst( )/insert at front thelist insertlast( )thelist insertlast( )thelist insertlast( )/insert at rear thelist displaylist()/display the list thelist deletefirst()thelist deletefirst()/delete first two items thelist displaylist()/end main(/end class firstlastapp /display again /////////////////////////////////////////////////////////////// |
22,715 | for simplicityin this program we've reduced the number of data items in each link from two to one this makes it easier to display the link contents (remember that in serious program there would be many more data itemsor reference to another object containing many data items this program inserts three items at the front of the listinserts three more at the endand displays the resulting list it then deletes the first two items and displays the list again here' the outputlist (first-->last) list (first-->last) notice how repeated insertions at the front of the list reverse the order of the itemswhile repeated insertions at the end preserve the order the double-ended list class is called the firstlastlist as discussedit has two data itemsfirst and lastwhich point to the first item and the last item in the list if there is only one item in the listboth first and last point to itand if there are no itemsthey are both null the class has new methodinsertlast()that inserts new item at the end of the list this process involves modifying last next to point to the new link and then changing last to point to the new linkas shown in figure first next next next next null last abefore insertion first next next next next last first bafter insertion null figure insertion at the end of list |
22,716 | linked lists the insertion and deletion routines are similar to those in single-ended list howeverboth insertion routines must watch out for the special case when the list is empty prior to the insertion that isif isempty(is truethen insertfirst(must set last to the new linkand insertlast(must set first to the new link if inserting at the beginning with insertfirst()first is set to point to the new linkalthough when inserting at the end with insertlast()last is set to point to the new link deleting from the start of the list is also special case if it' the last item on the listlast must be set to point to null in this case unfortunatelymaking list double-ended doesn' help you to delete the last link because there is still no reference to the next-to-last linkwhose next field would need to be changed to null if the last link were deleted to conveniently delete the last linkyou would need doubly linked listwhich we'll look at soon (of courseyou could also traverse the entire list to find the last linkbut that' not very efficient linked-list efficiency insertion and deletion at the beginning of linked list are very fast they involve changing only one or two referenceswhich takes ( time findingdeletingor inserting next to specific item requires searching throughon the averagehalf the items in the list this requires (ncomparisons an array is also (nfor these operationsbut the linked list is nevertheless faster because nothing needs to be moved when an item is inserted or deleted the increased efficiency can be significantespecially if copy takes much longer than comparison of courseanother important advantage of linked lists over arrays is that linked list uses exactly as much memory as it needs and can expand to fill all of available memory the size of an array is fixed when it' createdthis usually leads to inefficiency because the array is too largeor to running out of room because the array is too small vectorswhich are expandable arraysmay solve this problem to some extentbut they usually expand in fixed-sized increments (such as doubling the size of the array whenever it' about to overflowthis solution is still not as efficient use of memory as linked list abstract data types in this section we'll shift gears and discuss topic that' more general than linked listsabstract data types (adtswhat is an adtroughly speakingit' way of looking at data structurefocusing on what it does and ignoring how it does its job |
22,717 | stacks and queues are examples of adts we've already seen that both stacks and queues can be implemented using arrays before we return to discussion of adtslet' see how stacks and queues can be implemented using linked lists this discussion will demonstrate the "abstractnature of stacks and queueshow they can be considered separately from their implementation stack implemented by linked list when we created stack in "stacks and queues,we used an ordinary java array to hold the stack' data the stack' push(and pop(operations were actually carried out by array operations such as arr[++topdataand data arr[top--]which insert data intoand take it out ofan array we can also use linked list to hold stack' data in this case the push(and pop(operations would be carried out by operations like thelist insertfirst(dataand data thelist deletefirst(the user of the stack class calls push(and pop(to insert and delete items without knowingor needing to knowwhether the stack is implemented as an array or as linked list listing shows how stack class called linkstack can be implemented using the linklist class instead of an array (object purists would argue that the name linkstack should be simply stack because users of this class shouldn' need to know that it' implemented as list listing the linkstack java program /linkstack java /demonstrates stack implemented as list /to run this programc>java linkstackapp ///////////////////////////////////////////////////////////////class link public long ddata/data item public link next/next link in list |
22,718 | listing linked lists continued /public link(long dd/constructor ddata dd/public void displaylink(/display ourself system out print(ddata ")/end class link ///////////////////////////////////////////////////////////////class linklist private link first/ref to first item on list /public linklist(/constructor first null/no items on list yet /public boolean isempty(/true if list is empty return (first==null)/public void insertfirst(long dd/insert at start of list /make new link link newlink new link(dd)newlink next first/newlink --old first first newlink/first --newlink /public long deletefirst(/delete first item /(assumes list not emptylink temp first/save reference to link first first next/delete itfirst-->old next return temp ddata/return deleted link /public void displaylist(link current first/start at beginning of list while(current !null/until end of listcurrent displaylink()/print data current current next/move to next link system out println("") |
22,719 | listing continued //end class linklist ///////////////////////////////////////////////////////////////class linkstack private linklist thelist//public linkstack(/constructor thelist new linklist()//public void push(long /put item on top of stack thelist insertfirst( )//public long pop(/take item from top of stack return thelist deletefirst()//public boolean isempty(/true if stack is empty return thelist isempty()//public void displaystack(system out print("stack (top-->bottom)")thelist displaylist()///end class linkstack ///////////////////////////////////////////////////////////////class linkstackapp public static void main(string[argslinkstack thestack new linkstack()/make stack |
22,720 | listing linked lists continued thestack push( )thestack push( )/push items thestack displaystack()/display stack thestack push( )thestack push( )/push items thestack displaystack()/display stack thestack pop()thestack pop()/pop items thestack displaystack()/end main(/end class linkstackapp /display stack ///////////////////////////////////////////////////////////////the main(routine creates stack objectpushes two items on itdisplays the stackpushes two more itemsand displays the stack again finallyit pops two items and displays the stack third time here' the outputstack (top-->bottom) stack (top-->bottom) stack (top-->bottom) notice the overall organization of this program the main(routine in the linkstackapp class relates only to the linkstack class the linkstack class relates only to the linklist class there' no communication between main(and the linklist class more specificallywhen statement in main(calls the push(operation in the linkstack classthis method in turn calls insertfirst(in the linklist class to actually insert data similarlypop(calls deletefirst(to delete an itemand displaystack(calls displaylist(to display the stack to the class userwriting code in main()there is no difference between using the list-based linkstack class and using the array-based stack class from the stack java program (listing in queue implemented by linked list here' similar example of an adt implemented with linked list listing shows queue implemented as double-ended linked list |
22,721 | listing the linkqueue java program /linkqueue java /demonstrates queue implemented as double-ended list /to run this programc>java linkqueueapp ///////////////////////////////////////////////////////////////class link public long ddata/data item public link next/next link in list /public link(long /constructor ddata /public void displaylink(/display this link system out print(ddata ")//end class link ///////////////////////////////////////////////////////////////class firstlastlist private link first/ref to first item private link last/ref to last item /public firstlastlist(/constructor first null/no items on list yet last null/public boolean isempty(/true if no links return first==null/public void insertlast(long dd/insert at end of list link newlink new link(dd)/make new link ifisempty(/if empty listfirst newlink/first --newlink else last next newlink/old last --newlink last newlink/newlink <-last / |
22,722 | listing linked lists continued public long deletefirst(/delete first link /(assumes non-empty listlong temp first ddataif(first next =null/if only one item last null/null <-last first first next/first --old next return temp/public void displaylist(link current first/start at beginning while(current !null/until end of listcurrent displaylink()/print data current current next/move to next link system out println("")//end class firstlastlist ///////////////////////////////////////////////////////////////class linkqueue private firstlastlist thelist//public linkqueue(/constructor thelist new firstlastlist()/make -ended list //public boolean isempty(/true if queue is empty return thelist isempty()//public void insert(long /insertrear of queue thelist insertlast( )//public long remove(/removefront of queue return thelist deletefirst()//public void displayqueue(system out print("queue (front-->rear)") |
22,723 | listing continued thelist displaylist()///end class linkqueue ///////////////////////////////////////////////////////////////class linkqueueapp public static void main(string[argslinkqueue thequeue new linkqueue()thequeue insert( )/insert items thequeue insert( )thequeue displayqueue()/display queue thequeue insert( )thequeue insert( )/insert items thequeue displayqueue()/display queue thequeue remove()thequeue remove()/remove items thequeue displayqueue()/end main(/display queue ///////////////////////////////////////////////////////////////the program creates queueinserts two itemsinserts two more itemsand removes two itemsfollowing each of these operations the queue is displayed here' the outputqueue (front-->rear) queue (front-->rear) queue (front-->rear) here the methods insert(and remove(in the linkqueue class are implemented by the insertlast(and deletefirst(methods of the firstlastlist class we've substituted linked list for the array used to implement the queue in the queue java program (listing of the linkstack java and linkqueue java programs emphasize that stacks and queues are conceptual entitiesseparate from their implementations stack can be implemented equally well by an array or by linked list what' important about stack is |
22,724 | linked lists the push(and pop(operations and how they're usedit' not the underlying mechanism used to implement these operations when would you use linked list as opposed to an array as the implementation of stack or queueone consideration is how accurately you can predict the amount of data the stack or queue will need to hold if this isn' clearthe linked list gives you more flexibility than an array both are fastso speed is probably not major consideration data types and abstraction where does the term abstract data type come fromlet' look at the data type part of it first and then return to abstract data types the phrase data type covers lot of ground it was first applied to built-in types such as int and double this is probably what you first think of when you hear the term when you talk about primitive typeyou're actually referring to two thingsa data item with certain characteristics and permissible operations on that data for exampletype int variables in java can have whole-number values between - , , , and + , , , and the operators +-*/and so on can be applied to them the data type' permissible operations are an inseparable part of its identityunderstanding the type means understanding what operations can be performed on it with the advent of object-oriented programmingyou could now create your own data types using classes some of these data types represent numerical quantities that are used in ways similar to primitive types you canfor exampledefine class for time (with fields for hoursminutesseconds) class for fractions (with numerator and denominator fields)and class for extra-long numbers (characters in string represent the digitsall these classes can be added and subtracted like int and doubleexcept that in java you must use methods with functional notation like add(and sub(rather than operators like and the phrase data type seems to fit naturally with such quantity-oriented classes howeverit is also applied to classes that don' have this quantitative aspect in factany class represents data typein the sense that class is made up of data (fieldsand permissible operations on that data (methodsby extensionwhen data storage structure like stack or queue is represented by classit too can be referred to as data type stack is different in many ways from an intbut they are both defined as certain arrangement of data and set of operations on that data |
22,725 | abstraction the word abstract means "considered apart from detailed specifications or implementation an abstraction is the essence or important characteristics of something the office of presidentfor exampleis an abstractionconsidered apart from the individual who happens to occupy that office the powers and responsibilities of the office remain the samewhile individual office-holders come and go in object-oriented programmingthenan abstract data type is class considered without regard to its implementation it' description of the data in the class (fields) list of operations (methodsthat can be carried out on that dataand instructions on how to use these operations specifically excluded are the details of how the methods carry out their tasks as class useryou're told what methods to callhow to call themand the results you can expectbut not how they work the meaning of abstract data type is further extended when it' applied to data structures such as stacks and queues as with any classit means the data and the operations that can be performed on itbut in this context even the fundamentals of how the data is stored become invisible to the user users not only don' know how the methods workthey also don' know what structure is used to store the data for the stackthe user knows that push(and pop((and perhaps few other methodsexist and how they work the user doesn' (at least not usuallyneed to know how push(and pop(workor whether data is stored in an arraya linked listor some other data structure like tree the interface an adt specification is often called an interface it' what the class user sees--usually its public methods in stack classpush(and pop(and similar methods form the interface adt lists now that we know what an abstract data type iswe can mention another onethe list list (sometimes called linear listis group of items arranged in linear order that isthey're lined up in certain waylike beads on string or houses on street lists support certain fundamental operations you can insert an itemdelete an itemand usually read an item from specified location (the third itemsaydon' confuse the adt list with the linked list we've been discussing in this list is defined by its interfacethe specific methods used to interact with it this interface can be implemented by various structuresincluding arrays and linked lists the list is an abstraction of such data structures |
22,726 | linked lists adts as design tool the adt concept is useful aid in the software design process if you need to store datastart by considering the operations that need to be performed on that data do you need access to the last item insertedthe first onean item with specified keyan item in certain positionanswering such questions leads to the definition of an adt only after the adt is completely defined should you worry about the details of how to represent the data and how to code the methods that access the data by decoupling the specification of the adt from the implementation detailsyou can simplify the design process you also make it easier to change the implementation at some future time if user relates only to the adt interfaceyou should be able to change the implementation without "breakingthe user' code of courseonce the adt has been designedthe underlying data structure must be carefully chosen to make the specified operations as efficient as possible if you need random access to element nfor examplethe linked-list representation isn' so good because random access isn' an efficient operation for linked list you' be better off with an array note remember that the adt concept is only conceptual tool data storage structures are not divided cleanly into some that are adts and some that are used to implement adts linked listfor exampledoesn' need to be wrapped in list interface to be usefulit can act as an adt on its ownor it can be used to implement another data type such as queue linked list can be implemented using an arrayand an array-type structure can be implemented using linked list what' an adt and what' more basic structure must be determined in given context sorted lists in the linked lists we've seen thus farthere was no requirement that data be stored in order howeverfor certain applications it' useful to maintain the data in sorted order within the list list with this characteristic is called sorted list in sorted listthe items are arranged in sorted order by key value deletion is often limited to the smallest (or the largestitem in the listwhich is at the start of the listalthough sometimes find(and delete(methodswhich search through the list for specified linksare used as well in general you can use sorted list in most situations in which you use sorted array the advantages of sorted list over sorted array are speed of insertion (because elements don' need to be movedand the fact that list can expand to fill |
22,727 | available memorywhile an array is limited to fixed size howevera sorted list is somewhat more difficult to implement than sorted array later we'll look at one application for sorted listssorting data sorted list can also be used to implement priority queuealthough heap (see "heaps"is more common implementation the linklist workshop applet introduced at the beginning of this demonstrates sorted as well as unsorted lists to see how sorted lists workuse the new button to create new list with about linksand when promptedclick on the sorted button the result is list with data in sorted orderas shown in figure figure the linklist workshop applet with sorted list use the ins button to insert new item type in value that will fall somewhere in the middle of the list watch as the algorithm traverses the linkslooking for the appropriate insertion place when it finds the correct locationit inserts the new linkas shown in figure with the next press of insthe list will be redrawn to regularize its appearance you can also find specified link using the find button and delete specified link using the del button java code to insert an item in sorted list to insert an item in sorted listthe algorithm must first search through the list until it finds the appropriate place to put the itemthis is just before the first item that' largeras shown in figure |
22,728 | linked lists figure newly inserted link when the algorithm finds where to put itthe item can be inserted in the usual way by changing next in the new link to point to the next link and changing next in the previous link to point to the new link howeverwe need to consider some special casesthe link might need to be inserted at the beginning of the listor it might need to go at the end let' look at the codepublic void insert(long key/insert in order link newlink new link(key)/make new link link previous null/start at first link current first/until end of listwhile(current !null &key current ddata/or key currentprevious currentcurrent current next/go to next item if(previous==null/at beginning of list first newlink/first --newlink else /not at beginning previous next newlink/old prev --newlink newlink next current/newlink --old current /end insert(we need to maintain previous reference as we move alongso we can modify the previous link' next field to point to the new link after creating the new linkwe |
22,729 | prepare to search for the insertion point by setting current to first in the usual way we also set previous to nullthis step is important because later we'll use this null value to determine whether we're still at the beginning of the list the while loop is similar to those we've used before to search for the insertion pointbut there' an added condition the loop terminates when the key of the link currently being examined (current ddatais no longer smaller than the key of the link being inserted (key)this is the most usual casewhere key is inserted somewhere in the middle of the list howeverthe while loop also terminates if current is null this happens at the end of the list (the next field of the last element is null)or if the list is empty to begin with (first is nullwhen the while loop terminatesthenwe may be at the beginningthe middleor the end of the listor the list may be empty if we're at the beginningor the list is emptyprevious will be nullso we set first to the new link otherwisewe're in the middle of the listor at the endand we set previous next to the new link in any case we set the new link' next field to current if we're at the end of the listcurrent is nullso the new link' next field is appropriately set to this value the sortedlist java program the sortedlist java example shown in listing presents sortedlist class with insert()remove()and displaylist(methods only the insert(routine is different from its counterpart in non-sorted lists listing the sortedlist java program /sortedlist java /demonstrates sorted list /to run this programc>java sortedlistapp ///////////////////////////////////////////////////////////////class link public long ddata/data item public link next/next link in list /public link(long dd/constructor ddata dd/public void displaylink(/display this link system out print(ddata ") |
22,730 | listing linked lists continued /end class link ///////////////////////////////////////////////////////////////class sortedlist private link first/ref to first item on list /public sortedlist(/constructor first null/public boolean isempty(/true if no links return (first==null)/public void insert(long key/insertin order link newlink new link(key)/make new link link previous null/start at first link current first/until end of listwhile(current !null &key current ddata/or key currentprevious currentcurrent current next/go to next item if(previous==null/at beginning of list first newlink/first --newlink else /not at beginning previous next newlink/old prev --newlink newlink next current/newlink --old current /end insert(/public link remove(/return delete first link /(assumes non-empty listlink temp first/save first first first next/delete first return temp/return value /public void displaylist(system out print("list (first-->last)")link current first/start at beginning of list |
22,731 | listing continued while(current !null/until end of listcurrent displaylink()/print data current current next/move to next link system out println("")/end class sortedlist ///////////////////////////////////////////////////////////////class sortedlistapp public static void main(string[args/create new list sortedlist thesortedlist new sortedlist()thesortedlist insert( )/insert items thesortedlist insert( )thesortedlist displaylist()/display list thesortedlist insert( )thesortedlist insert( )thesortedlist insert( )/insert more items thesortedlist displaylist()/display list thesortedlist remove()/remove an item thesortedlist displaylist()/display list /end main(/end class sortedlistapp ///////////////////////////////////////////////////////////////in main(we insert two items with key values and then we insert three more itemswith values and these values are inserted at the beginning of the listin the middleand at the endshowing that the insert(routine correctly handles these special cases finallywe remove one itemto show removal is always from the front of the list after each changethe list is displayed here' the output from sortedlist javalist (first-->last) list (first-->last) list (first-->last) |
22,732 | linked lists efficiency of sorted linked lists insertion and deletion of arbitrary items in the sorted linked list require (ncomparisons ( / on the averagebecause the appropriate location must be found by stepping through the list howeverthe minimum value can be foundor deletedin ( time because it' at the beginning of the list if an application frequently accesses the minimum itemand fast insertion isn' criticalthen sorted linked list is an effective choice priority queue might be implemented by sorted linked listfor example list insertion sort sorted list can be used as fairly efficient sorting mechanism suppose you have an array of unsorted data items if you take the items from the array and insert them one by one into the sorted listthey'll be placed in sorted order automatically if you then remove them from the list and put them back in the arraythe array will be sorted this type of sort turns out to be substantially more efficient than the more usual insertion sort within an arraydescribed in "simple sorting,because fewer copies are necessary it' still an ( process because inserting each item into the sorted list involves comparing new item with an average of half the items already in the listand there are items to insertresulting in about / comparisons howevereach item is copied only twiceonce from the array to the list and once from the list to the array * copies compares favorably with the insertion sort within an arraywhere there are about copies listing shows the listinsertionsort java programwhich starts with an array of unsorted items of type linkinserts them into sorted list (using constructor)and then removes them and places them back into the array listing the listinsertionsort java program /listinsertionsort java /demonstrates sorted list used for sorting /to run this programc>java listinsertionsortapp ///////////////////////////////////////////////////////////////class link public long ddata/data item public link next/next link in list /public link(long dd/constructor ddata dd/ |
22,733 | listing continued /end class link ///////////////////////////////////////////////////////////////class sortedlist private link first/ref to first item on list /public sortedlist(/constructor (no argsfirst null/initialize list /public sortedlist(link[linkarr/constructor (array /as argumentfirst null/initialize list for(int = <linkarr lengthj++/copy array insertlinkarr[ )/to list /public void insert(link /insert (in orderlink previous null/start at first link current first/until end of listwhile(current !null & ddata current ddata/or key currentprevious currentcurrent current next/go to next item if(previous==null/at beginning of list first /first -- else /not at beginning previous next /old prev -- next current/ --old current /end insert(/public link remove(/return delete first link /(assumes non-empty listlink temp first/save first first first next/delete first return temp/return value //end class sortedlist |
22,734 | listing linked lists continued ///////////////////////////////////////////////////////////////class listinsertionsortapp public static void main(string[argsint size /create array of links link[linkarray new link[size]for(int = <sizej++/fill array with links /random number int (int)(java lang math random()* )link newlink new link( )/make link linkarray[jnewlink/put in array /display array contents system out print("unsorted array")for(int = <sizej++system out printlinkarray[jddata )system out println("")/create new list /initialized with array sortedlist thesortedlist new sortedlist(linkarray)for(int = <sizej++/links from list to array linkarray[jthesortedlist remove()/display array contents system out print("sorted array")for(int = <sizej++system out print(linkarray[jddata ")system out println("")/end main(/end class listinsertionsortapp ///////////////////////////////////////////////////////////////this program displays the values in the array before the sorting operation and again afterward here' some sample outputunsorted array sorted array |
22,735 | the output will be different each time because the initial values are generated randomly new constructor for sortedlist takes an array of link objects as an argument and inserts the entire contents of this array into the newly created list by doing soit helps make things easier for the client (the main(routinewe've also made change to the insert(routine in this program it now accepts link object as an argumentrather than long we do this so we can store link objects in the array and insert them directly into the list in the sortedlist java program (listing )it was more convenient to have the insert(routine create each link objectusing the long value passed as an argument the downside of the list insertion sortcompared with an array-based insertion sortis that it takes somewhat more than twice as much memorythe array and linked list must be in memory at the same time howeverif you have sorted linked list class handythe list insertion sort is convenient way to sort arrays that aren' too large doubly linked lists let' examine another variation on the linked listthe doubly linked list (not to be confused with the double-ended listwhat' the advantage of doubly linked lista potential problem with ordinary linked lists is that it' difficult to traverse backward along the list statement like current=current next steps conveniently to the next linkbut there' no corresponding way to go to the previous link depending on the applicationthis limitation could pose problems for exampleimagine text editor in which linked list is used to store the text each text line on the screen is stored as string object embedded in link when the editor' user moves the cursor downward on the screenthe program steps to the next link to manipulate or display the new line but what happens if the user moves the cursor upwardin an ordinary linked listyou would need to return current (or its equivalentto the start of the list and then step all the way down again to the new current link this isn' very efficient you want to make single step upward the doubly linked list provides this capability it allows you to traverse backward as well as forward through the list the secret is that each link has two references to other links instead of one the first is to the next linkas in ordinary lists the second is to the previous link this type of list is shown in figure |
22,736 | linked lists first last next next next next prev prev prev prev null null figure doubly linked list the beginning of the specification for the link class in doubly linked list looks like thisclass link public long ddatapublic link nextpublic link previous/data item /next link in list /previous link in list the downside of doubly linked lists is that every time you insert or delete link you must deal with four links instead of twotwo attachments to the previous link and two attachments to the following one alsoof courseeach link is little bigger because of the extra reference doubly linked list doesn' necessarily need to be double-ended list (keeping reference to the last element on the listbut creating it this way is usefulso we'll include it in our example we'll show the complete listing for the doublylinked java program soonbut first let' examine some of the methods in its doublylinkedlist class traversal two display methods demonstrate traversal of doubly linked list the displayforward(method is the same as the displaylist(method we've seen in ordinary linked lists the displaybackward(method is similar but starts at the last element in the list and proceeds toward the start of the listgoing to each element' previous field this code fragment shows how this process workslink current lastwhile(current !nullcurrent current previous/start at end /until start of list/move to previous link |
22,737 | incidentallysome people take the view thatbecause you can go either way equally easily on doubly linked listthere is no preferred direction and therefore terms like previous and next are inappropriate if you preferyou can substitute directionneutral terms such as left and right insertion we've included several insertion routines in the doublylinkedlist class the insertfirst(method inserts at the beginning of the listinsertlast(inserts at the endand insertafter(inserts following an element with specified key unless the list is emptythe insertfirst(routine changes the previous field in the old first link to point to the new link and changes the next field in the new link to point to the old first link finallyit sets first to point to the new link this process is shown in figure old first link first next next next next prev prev prev prev null last next prev null new link figure insertion at the beginning if the list is emptythe last field must be changed instead of the first previous field here' the codeifisempty(last newlinkelse first previous newlinknewlink next firstfirst newlink/if empty list/newlink <-last /newlink <-old first /newlink --old first /first --newlink |
22,738 | linked lists the insertlast(method is the same process applied to the end of the listit' mirror image of insertfirst(the insertafter(method inserts new link following the link with specified key value it' bit more complicated because four connections must be made firstthe link with the specified key value must be found this procedure is handled the same way as the find(routine in the linklist java program (listing thenassuming we're not at the end of the listtwo connections must be made between the new link and the next linkand two more between current and the new link this process is shown in figure current first last next next next next prev prev prev prev null null next prev figure insertion at an arbitrary location if the new link will be inserted at the end of the listits next field must point to nulland last must point to the new link here' the insertafter(code that deals with the linksif(current==last/if last linknewlink next null/newlink --null last newlink/newlink <-last else /not last linknewlink next current next/newlink --old next /newlink <-old next current next previous newlink |
22,739 | newlink previous currentcurrent next newlink/old current <-newlink /old current --newlink perhaps you're unfamiliar with the use of two dot operators in the same expression it' natural extension of single dot operator the expression current next previous means the previous field of the link referred to by the next field in the link current deletion there are three deletion routinesdeletefirst()deletelast()and deletekey(the first two are fairly straightforward in deletekey()the key being deleted is current assuming the link to be deleted is neither the first nor the last one in the listthe next field of current previous (the link before the one being deletedis set to point to current next (the link following the one being deleted)and the previous field of current next is set to point to current previous this disconnects the current link from the list figure shows how this disconnection looksand the following two statements carry it outcurrent previous next current nextcurrent next previous current previouscurrent prev next first last null prev current current next next next prev prev null figure deleting an arbitrary link special cases arise if the link to be deleted is either the first or last in the list because first or last must be set to point to the next or the previous link here' the code from deletekey(for dealing with link connectionsif(current==firstfirst current nextelse /first item/first --old next /not first /old previous --old next |
22,740 | linked lists current previous next current nextif(current==lastlast current previouselse /last item/old previous <-last /not last /old previous <-old next current next previous current previousthe doublylinked java program listing shows the complete doublylinked java programwhich includes all the routines just discussed listing the doublylinked java program /doublylinked java /demonstrates doubly-linked list /to run this programc>java doublylinkedapp ///////////////////////////////////////////////////////////////class link public long ddata/data item public link next/next link in list public link previous/previous link in list /public link(long /constructor ddata /public void displaylink(/display this link system out print(ddata ")//end class link ///////////////////////////////////////////////////////////////class doublylinkedlist private link first/ref to first item private link last/ref to last item /public doublylinkedlist(/constructor first null/no items on list yet last null |
22,741 | listing continued /public boolean isempty(/true if no links return first==null/public void insertfirst(long dd/insert at front of list link newlink new link(dd)/make new link ifisempty(/if empty listlast newlink/newlink <-last else first previous newlink/newlink <-old first newlink next first/newlink --old first first newlink/first --newlink /public void insertlast(long dd/insert at end of list link newlink new link(dd)/make new link ifisempty(/if empty listfirst newlink/first --newlink else last next newlink/old last --newlink newlink previous last/old last <-newlink last newlink/newlink <-last /public link deletefirst(/delete first link /(assumes non-empty listlink temp firstif(first next =null/if only one item last null/null <-last else first next previous null/null <-old next first first next/first --old next return temp/public link deletelast(/delete last link |
22,742 | listing linked lists continued /(assumes non-empty listlink temp lastif(first next =null/if only one item first null/first --null else last previous next null/old previous --null last last previous/old previous <-last return temp//insert dd just after key public boolean insertafter(long keylong dd/(assumes non-empty listlink current first/start at beginning while(current ddata !key/until match is foundcurrent current next/move to next link if(current =nullreturn false/didn' find it link newlink new link(dd)/make new link if(current==last/if last linknewlink next null/newlink --null last newlink/newlink <-last else /not last linknewlink next current next/newlink --old next /newlink <-old next current next previous newlinknewlink previous current/old current <-newlink current next newlink/old current --newlink return true/found itdid insertion /public link deletekey(long key/delete item wgiven key /(assumes non-empty listlink current first/start at beginning |
22,743 | listing continued while(current ddata !keycurrent current nextif(current =nullreturn nullif(current==firstfirst current nextelse /until match is found/move to next link /didn' find it /found itfirst item/first --old next /not first /old previous --old next current previous next current nextif(current==lastlast current previouselse /last item/old previous <-last /not last /old previous <-old next current next previous current previousreturn current/return value /public void displayforward(system out print("list (first-->last)")link current first/start at beginning while(current !null/until end of listcurrent displaylink()/display data current current next/move to next link system out println("")/public void displaybackward(system out print("list (last-->first)")link current last/start at end while(current !null/until start of listcurrent displaylink()/display data current current previous/move to previous link |
22,744 | listing linked lists continued system out println("")//end class doublylinkedlist ///////////////////////////////////////////////////////////////class doublylinkedapp public static void main(string[args/make new list doublylinkedlist thelist new doublylinkedlist()thelist insertfirst( )thelist insertfirst( )thelist insertfirst( )/insert at front thelist insertlast( )thelist insertlast( )thelist insertlast( )/insert at rear thelist displayforward()thelist displaybackward()/display list forward /display list backward thelist deletefirst()thelist deletelast()thelist deletekey( )/delete first item /delete last item /delete item with key thelist displayforward()/display list forward thelist insertafter( )thelist insertafter( )/insert after /insert after thelist displayforward()/display list forward /end main(/end class doublylinkedapp ///////////////////////////////////////////////////////////////in main(we insert some items at the beginning of the list and at the enddisplay the items going both forward and backwarddelete the first and last items and the item with key display the list again (forward only)insert two items using the insertafter(methodand display the list again here' the output |
22,745 | list (first-->last) list (last-->first) list (first-->last) list (first-->last) the deletion methods and the insertafter(method assume that the list isn' empty although for simplicity we don' show it in main()isempty(should be used to verify that there' something in the list before attempting such insertions and deletions doubly linked list as basis for deques doubly linked list can be used as the basis for dequementioned in the preceding in deque you can insert and delete at either endand the doubly linked list provides this capability iterators we've seen how the user of list can find link with given key using find(method the method starts at the beginning of the list and examines each link until it finds one matching the search key other operations we've looked atsuch as deleting specified link or inserting before or after specified linkalso involve searching through the list to find the specified link howeverthese methods don' give the user any control over the traversal to the specified item suppose you wanted to traverse listperforming some operation on certain links for exampleimagine personnel file stored as linked list you might want to increase the wages of all employees who were being paid minimum wagewithout affecting employees already above the minimum or suppose that in list of mailorder customersyou decided to delete all customers who had not ordered anything in six months in an arraysuch operations are easy because you can use an array index to keep track of your position you can operate on one itemthen increment the index to point to the next itemand see if that item is suitable candidate for the operation howeverin linked listthe links don' have fixed index numbers how can we provide list' user with something analogous to an array indexyou could repeatedly use find(to look for appropriate items in listbut that approach requires many comparisons to find each link it' far more efficient to step from link to linkchecking whether each one meets certain criteria and performing the appropriate operation if it does |
22,746 | linked lists reference in the list itselfas users of list classwhat we need is access to reference that can point to any arbitrary link this waywe can examine or modify the link we should be able to increment the reference so we can traverse along the listlooking at each link in turnand we should be able to access the link pointed to by the reference assuming we create such referencewhere will it be installedone possibility is to use field in the list itselfcalled current or something similar you could access link using current and increment current to move to the next link one problem with this approach is that you might need more than one such referencejust as you often use several array indices at the same time how many would be appropriatethere' no way to know how many the user might need thusit seems easier to allow the user to create as many such references as necessary to make this possible in an object-oriented languageit' natural to embed each reference in class object this object can' be the same as the list class because there' only one list objectso it is normally implemented as separate class an iterator class objects containing references to items in data structuresused to traverse these structuresare commonly called iterators (or sometimesas in certain java classesenumeratorshere' preliminary idea of how they lookclass listiterator(private link currentthe current field contains reference to the link the iterator currently points to (the term points as used here doesn' refer to pointers in ++we're using it in its generic sense to mean "refers to "to use such an iteratorthe user might create list and then create an iterator object associated with the list actuallyas it turns outletting the list create the iterator is easierso it can pass the iterator certain informationsuch as reference to its first field thuswe add getiterator(method to the list classthis method returns suitable iterator object to the user here' some abbreviated code in main(that shows how the class user would invoke an iteratorpublic static void mainlinklist thelist new linklist()listiterator iter thelist getiterator()/make list /make iter |
22,747 | link alink iter getcurrent()iter nextlink()/access link at iterator /move iter to next link after we've made the iterator objectwe can use it to access the link it points to or increment it so it points to the next linkas shown in the second two statements we call the iterator object iter to emphasize that you could make more iterators (iter and so onthe same way the iterator always points to some link in the list it' associated with the listbut it' not the same as the list or the same as link figure shows two iterators pointing to links in list linked list first null next next next next list iterator current list iterator current figure list iterators additional iterator features we've seen several programs in which the use of previous field made performing certain operations simplersuch as deleting link from an arbitrary location such field is also useful in an iterator alsoit may be that the iterator will need to change the value of the list' first field--for instanceif an item is inserted or deleted at the beginning of the list if the iterator is an object of separate classhow can it access private fieldsuch as firstin the listone solution is for the list to pass reference from itself to the iterator when it creates the iterator this reference is stored in field in the iterator |
22,748 | linked lists the list must then provide public methods that allow the iterator to change first these linklist methods are getfirst(and setfirst((the weakness of this approach is that these methods allow anyone to change firstwhich introduces an element of risk here' revised (although still incompleteiterator class that incorporates these additional fieldsalong with reset(and nextlink(methodsclass listiterator(private link currentprivate link previousprivate linklist ourlist/reference to current link /reference to previous link /reference to "parentlist public void reset(/set to start of list current ourlist getfirst()/current --first previous null/previous --null public void nextlink(/go to next link previous current/set previous to this current current next/set this to next we might notefor you old-time +programmersthat in +the connection between the iterator and the list is typically provided by making the iterator class friend of the list class howeverjava has no friend classeswhich are controversial in any case because they are chink in the armor of data hiding iterator methods additional methods can make the iterator flexible and powerful class all operations previously performed by the class that involve iterating through the listsuch as insertafter()are more naturally performed by the iterator in our example the iterator includes the following methodsreset()--sets the iterator to the start of the list nextlink()--moves the iterator to the next link getcurrent()--returns the link at the iterator atend()--returns true if the iterator is at the end of the list |
22,749 | insertafter()--inserts new link after the iterator insertbefore()--inserts new link before the iterator deletecurrent()--deletes the link at the iterator the user can position the iterator using reset(and nextlink()check whether it' at the end of the list with atend()and perform the other operations shown deciding which tasks should be carried out by an iterator and which by the list itself is not always easy an insertbefore(method works best in the iteratorbut an insertfirst(routine that always inserts at the beginning of the list might be more appropriate in the list class we've kept displaylist(routine in the listbut this operation could also be handled with getcurrent(and nextlink(calls to the iterator the interiterator java program the interiterator java program includes an interactive interface that permits the user to control the iterator directly after you've started the programyou can perform the following actions by typing the appropriate letters--show the list contents --reset the iterator to the start of the list --go to the next link --get the contents of the current link --insert before the current link --insert new link after the current link --delete the current link listing shows the complete interiterator java program listing the interiterator java program /interiterator java /demonstrates iterators on linked listlistiterator /to run this programc>java interiterapp import java io */for / ///////////////////////////////////////////////////////////////class link public long ddata/data item |
22,750 | listing linked lists continued public link next/next link in list /public link(long dd/constructor ddata dd/public void displaylink(/display ourself system out print(ddata ")/end class link ///////////////////////////////////////////////////////////////class linklist private link first/ref to first item on list /public linklist(/constructor first null/no items on list yet /public link getfirst(/get value of first return first/public void setfirst(link /set first to new link first /public boolean isempty(/true if list is empty return first==null/public listiterator getiterator(/return iterator return new listiterator(this)/initialized with /this list /public void displaylist(link current first/start at beginning of list while(current !null/until end of listcurrent displaylink()/print data current current next/move to next link system out println("") |
22,751 | listing continued //end class linklist ///////////////////////////////////////////////////////////////class listiterator private link current/current link private link previous/previous link private linklist ourlist/our linked list //public listiterator(linklist list/constructor ourlist listreset()//public void reset(/start at 'firstcurrent ourlist getfirst()previous null//public boolean atend(/true if last link return (current next==null)//public void nextlink(/go to next link previous currentcurrent current next//public link getcurrent(/get current link return current//public void insertafter(long dd/insert after /current link link newlink new link(dd)ifourlist isempty(/empty list ourlist setfirst(newlink)current newlink |
22,752 | listing linked lists continued else /not empty newlink next current nextcurrent next newlinknextlink()/point to new link //public void insertbefore(long dd/insert before /current link link newlink new link(dd)if(previous =null/beginning of list /(or empty listnewlink next ourlist getfirst()ourlist setfirst(newlink)reset()else /not beginning newlink next previous nextprevious next newlinkcurrent newlink//public long deletecurrent(/delete item at current long value current ddataif(previous =null/beginning of list ourlist setfirst(current next)reset()else /not beginning previous next current nextifatend(reset()else |
22,753 | listing continued current current nextreturn value///end class listiterator ///////////////////////////////////////////////////////////////class interiterapp public static void main(string[argsthrows ioexception linklist thelist new linklist()/new list listiterator iter thelist getiterator()/new iter long valueiter insertafter( )iter insertafter( )iter insertafter( )iter insertbefore( )/insert items while(truesystem out print("enter first letter of showreset")system out print("nextgetbeforeafterdelete")system out flush()int choice getchar()/get user' option switch(choicecase ' '/show list if!thelist isempty(thelist displaylist()else system out println("list is empty")breakcase ' '/reset (to firstiter reset()breakcase ' '/advance to next item if!thelist isempty(&!iter atend(iter nextlink()else |
22,754 | listing linked lists continued system out println("can' go to next link")breakcase ' '/get current item if!thelist isempty(value iter getcurrent(ddatasystem out println("returned value)else system out println("list is empty")breakcase ' '/insert before current system out print("enter value to insert")system out flush()value getint()iter insertbefore(value)breakcase ' '/insert after current system out print("enter value to insert")system out flush()value getint()iter insertafter(value)breakcase ' '/delete current item if!thelist isempty(value iter deletecurrent()system out println("deleted value)else system out println("can' delete")breakdefaultsystem out println("invalid entry")/end switch /end while /end main(//public static string getstring(throws ioexception inputstreamreader isr new inputstreamreader(system in) |
22,755 | listing continued bufferedreader br new bufferedreader(isr)string br readline()return //public static char getchar(throws ioexception string getstring()return charat( )//public static int getint(throws ioexception string getstring()return integer parseint( )///end class interiterapp ///////////////////////////////////////////////////////////////the main(routine inserts four items into the listusing an iterator and its insertafter(method then it waits for the user to interact with it in the following sample interactionthe user displays the listresets the iterator to the beginninggoes forward two linksgets the current link' key value (which is )inserts before thisinserts after the and displays the list againenter first letter of showresetnextgetbeforeafterdeletes enter first letter of showresetnextgetbeforeafterdeleter enter first letter of showresetnextgetbeforeafterdeleten enter first letter of showresetnextgetbeforeafterdeleten enter first letter of showresetnextgetbeforeafterdeleteg returned enter first letter of showresetnextgetbeforeafterdeleteb enter value to insert |
22,756 | linked lists enter first letter of showresetnextgetbeforeafterdeletea enter value to insert enter first letter of showresetnextgetbeforeafterdeletes experimenting with the interiterator java program will give you feeling for how the iterator moves along the links and how it can insert and delete links anywhere in the list where does the iterator pointone of the design issues in an iterator class is deciding where the iterator should point following various operations when you delete an item with deletecurrent()should the iterator end up pointing to the next itemto the previous itemor back at the beginning of the listkeeping the iterator in the vicinity of the deleted item is convenient because the chances are the class user will be carrying out other operations there howeveryou can' move it to the previous item because there' no way to reset the list' previous field to the previous item (you would need doubly linked list for that task our solution is to move the iterator to the link following the deleted link if we've just deleted the item at the end of the listthe iterator is set to the beginning of the list following calls to insertbefore(and insertafter()we return with current pointing to the newly inserted item the atend(method there' another question about the atend(method it could return true when the iterator points to the last valid link in the listor it could return true when the iterator points past the last link (and is thus not pointing to valid linkwith the first approacha loop condition used to iterate through the list becomes awkward because you need to perform an operation on the last link before checking whether it is the last link (and terminating the loop if it ishoweverthe second approach doesn' allow you to find out you're at the end of the list until it' too late to do anything with the last link (you couldn' look for the last link and then delete itfor example this is because when atend(became truethe iterator would no longer point to the last link (or indeed any valid link)and you can' "back upthe iterator in singly linked list we take the first approach this waythe iterator always points to valid linkalthough you must be careful when writing loop that iterates through the listas we'll see next |
22,757 | iterative operations as we notedan iterator allows you to traverse the listperforming operations on certain data items here' code fragment that displays the list contentsusing an iterator instead of the list' displaylist(methoditer reset()long value iter getcurrent(ddatasystem out println(value ")while!iter atend(iter nextlink()long value iter getcurrent(ddatasystem out println(value ")/start at first /display link /until end/go to next link/display it although we don' do so hereyou should check with isempty(to be sure the list is not empty before calling getcurrent(the following code shows how you could delete all items with keys that are multiples of we show only the revised main(routineeverything else is the same as in interiterator java (listing class interiterapp public static void main(string[argsthrows ioexception linklist thelist new linklist()/new list listiterator iter thelist getiterator()/new iter iter insertafter( )iter insertafter( )iter insertafter( )iter insertafter( )iter insertafter( )/insert links thelist displaylist()/display list iter reset()link alink iter getcurrent()if(alink ddata = iter deletecurrent()while!iter atend(/start at first link /get it /if divisible by /delete it /until end of list |
22,758 | linked lists iter nextlink()alink iter getcurrent()if(alink ddata = iter deletecurrent()thelist displaylist()/end main(/end class interiterapp /go to next link /get link /if divisible by /delete it /display list we insert five links and display the list then we iterate through the listdeleting those links with keys divisible by and display the list again here' the output againalthough we don' show it hereit' important to check whether the list is empty before calling deletecurrent(other methods you could create other useful methods for the listiterator class for examplea find(method would return an item with specified key valueas we've seen when find(is list method replace(method could replace items that had certain key values with other items because it' singly linked listyou can iterate along it only in the forward direction if doubly linked list were usedyou could go either wayallowing operations such as deletion from the end of the listjust as with non-iterators this capability would probably be convenience in some applications summary linked list consists of one linkedlist object and number of link objects the linkedlist object contains referenceoften called firstto the first link in the list each link object contains data and referenceoften called nextto the next link in the list next value of null signals the end of the list inserting an item at the beginning of linked list involves changing the new link' next field to point to the old first link and changing first to point to the new item |
22,759 | deleting an item at the beginning of list involves setting first to point to first next to traverse linked listyou start at first and then go from link to linkusing each link' next field to find the next link link with specified key value can be found by traversing the list once foundan item can be displayeddeletedor operated on in other ways new link can be inserted before or after link with specified key valuefollowing traversal to find this link double-ended list maintains pointer to the last link in the listoften called lastas well as to the first double-ended list allows insertion at the end of the list an abstract data type (adtis data storage class considered without reference to its implementation stacks and queues are adts they can be implemented using either arrays or linked lists in sorted linked listthe links are arranged in order of ascending (or sometimes descendingkey value insertion in sorted list takes (ntime because the correct insertion point must be found deletion of the smallest link takes ( time in doubly linked listeach link contains reference to the previous link as well as the next link doubly linked list permits backward traversal and deletion from the end of the list an iterator is referenceencapsulated in class objectthat points to link in an associated list iterator methods allow the user to move the iterator along the list and access the link currently pointed to an iterator can be used to traverse through listperforming some operation on selected links (or all linksquestions these questions are intended as self-test for readers answers may be found in appendix |
22,760 | linked lists which of the following is not truea reference to class object can be used to access public methods in the object has size dependant on its class has the data type of the class does not hold the object itself access to the links in linked list is usually through the link when you create reference to link in linked listit must refer to the first link must refer to the link pointed to by current must refer to the link pointed to by next can refer to any link you want how many references must you change to insert link in the middle of singly linked list how many references must you change to insert link at the end of singly linked list in the insertfirst(method in the linklist java program (listing )the statement newlink next=firstmeans that the next new link to be inserted will refer to first first will refer to the new link the next field of the new link will refer to the old first link newlink next will refer to the new first link in the list assuming current points to the next-to-last link in singly linked listwhat statement will delete the last link from the list when all references to link are changed to refer to something elsewhat happens to the link double-ended list can be accessed from either end is different name for doubly linked list has pointers running both forward and backward between links has its first link connected to its last link |
22,761 | special case often occurs for insertion and deletion routines when list is assuming copy takes longer than comparisonis it faster to delete an item with certain key from linked list or from an unsorted array how many times would you need to traverse singly linked list to delete the item with the largest key of the lists discussed in this which one would be best for implementing queue which of the following is not trueiterators would be useful if you wanted to do an insertion sort on linked list insert new link at the beginning of list swap two links at arbitrary locations delete all links with certain key value which do you think would be better choice to implement stacka singly linked list or an arrayexperiments carrying out these experiments will help to provide insights into the topics covered in the no programming is involved use the linklist workshop applet to execute insertfindand delete operations on both sorted and unsorted lists for the operations demonstrated by this appletis there any advantage to the sorted list modify main(in the linklist java program (listing so that it continuously inserts links into the list until memory is exhausted after each , itemshave it display the number of items inserted so far this wayyou can learn approximately how many links list can hold in your particular machine (of coursethe number will vary depending on what other programs are in memory and many other factors don' try this experiment if it will crash your institution' network programming projects writing programs that solve the programming projects helps to solidify your understanding of the material and demonstrates how the concepts are applied |
22,762 | linked lists (as noted in the introductionqualified instructors may obtain completed solutions to the programming projects on the publisher' web site implement priority queue based on sorted linked list the remove operation on the priority queue should remove the item with the smallest key implement deque based on doubly linked list (see programming project in the preceding the user should be able to carry out the normal operations on the deque circular list is linked list in which the last link points back to the first link there are many ways to design circular list sometimes there is pointer to the "startof the list howeverthis makes the list less like real circle and more like an ordinary list that has its end attached to its beginning make class for singly linked circular list that has no end and no beginning the only access to the list is single referencecurrentthat can point to any link on the list this reference can move around the list as needed (see programming project for situation in which such circular list is ideally suited your list should handle insertionsearchingand deletion you may find it convenient if these operations take place one link downstream of the link pointed to by current (because the upstream link is singly linkedyou can' get at it without going all the way around the circle you should also be able to display the list (although you'll need to break the circle at some arbitrary point to print it on the screena step(method that moves current along to the next link might come in handy too implement stack class based on the circular list of programming project this exercise is not too difficult (howeverimplementing queue can be harderunless you make the circular list doubly linked the josephus problem is famous mathematical puzzle that goes back to ancient times there are many stories to go with the puzzle one is that josephus was one of group of jews who were about to be captured by the romans rather than be enslavedthey chose to commit suicide they arranged themselves in circle andstarting at certain personstarted counting off around the circle every nth person had to leave the circle and commit suicide josephus decided he didn' want to dieso he arranged the rules so he would be the last person left if there were (say peopleand he was the seventh person from the start of the circlewhat number should he tell them to use for counting offthe problem is made much more complicated because the circle shrinks as the counting continues create an application that uses circular linked list (like that in programming project to model this problem inputs are the number of people in the circlethe number used for counting offand the number of the person where |
22,763 | counting starts (usually the output is the list of persons being eliminated when person drops out of the circlecounting starts again from the person who was on his left (assuming you go around clockwisehere' an example there are seven people numbered through and you start at and count off by threes people will be eliminated in the order number will be left let' try something little differenta two-dimensional linked listwhich we'll call matrix this is the list analogue of two-dimensional array it might be useful in applications such as spreadsheet programs if spreadsheet is based on an arrayand you insert new row near the topyou must move every cell in the lower rows * cellswhich is potentially slow process if the spreadsheet is implemented by matrixyou need only change pointers for simplicitywe'll assume singly linked approach (although double-linked approach would probably be more appropriate for spreadsheeteach link (except those on the top row and left sideis pointed to by the link directly above it and by the link on its left you can start at the upper-left link and navigate tosaythe link on the third row and fifth column by following the pointers down two rows and right four columns assume your matrix is created with specified dimensions ( by for exampleyou should be able to insert values in specified links and display the contents of the matrix |
22,764 | recursion in this triangular numbers factorials anagrams recursion is programming technique in which method (functioncalls itself this may sound like strange thing to door even catastrophic mistake recursion ishoweverone of the most interestingand one of the most surprisingly effectivetechniques in programming like pulling yourself up by your bootstraps (you do have bootstrapsdon' you?)recursion seems incredible when you first encounter it howeverit not only worksit also provides unique conceptual framework for solving many problems in this we'll examine numerous examples to show the wide variety of situations to which recursion can be applied we will calculate triangular numbers and factorialsgenerate anagramsperform recursive binary searchsolve the towers of hanoi puzzleand investigate sorting technique called mergesort workshop applets are provided to demonstrate the towers of hanoi and mergesort we'll also discuss the strengths and weaknesses of recursionand show how recursive approach can be transformed into stack-based approach triangular numbers it' said that the pythagoriansa band of mathematicians in ancient greece who worked under pythagoras (of pythagorian theorem fame)felt mystical connection with the series of numbers (where the means the series continues indefinitelycan you find the next member of this seriesthe nth term in the series is obtained by adding to the previous term thusthe second term is found by adding to the first term (which is )giving the third term is added to the second term (which is giving and so on recursive binary search the towers of hanoi mergesort eliminating recursion some interesting recursive applications |
22,765 | recursion the numbers in this series are called triangular numbers because they can be visualized as triangular arrangement of objectsshown as little squares in figure # # # # # # # figure the triangular numbers finding the nth term using loop suppose you wanted to find the value of some arbitrary nth term in the series--say the fourth term (whose value is how would you calculate itlooking at figure you might decide that the value of any term can be obtained by adding up all the vertical columns of squares in this column in this column in this column in this column total figure triangular number as columns in the fourth termthe first column has four little squaresthe second column has threeand so on adding + + + gives |
22,766 | the following triangle(method uses this column-based technique to find triangular number it sums all the columnsfrom height of to height of int triangle(int nint total while( total total --nreturn total/until is /add (column heightto total /decrement column height the method cycles around the loop timesadding to total the first timen- the second timeand so on down to quitting the loop when becomes finding the nth term using recursion the loop approach may seem straightforwardbut there' another way to look at this problem the value of the nth term can be thought of as the sum of only two thingsinstead of whole series they are the first (tallestcolumnwhich has the value the sum of all the remaining columns this is shown in figure in the remaining columns in the first column total figure triangular number as column plus triangle |
22,767 | recursion finding the remaining columns if we knew about method that found the sum of all the remaining columnswe could write our triangle(methodwhich returns the value of the nth triangular numberlike thisint triangle(int nreturnn sumremainingcolumns( )/(incomplete versionbut what have we gained hereit looks like writing the sumremainingcolumns(method is just as hard as writing the triangle(method in the first place notice in figure howeverthat the sum of all the remaining columns for term is the same as the sum of all the columns for term - thusif we knew about method that summed all the columns for term nwe could call it with an argument of - to find the sum of all the remaining columns for term nint triangle(int nreturnn sumallcolumns( - )/(incomplete versionbut when you think about itthe sumallcolumns(method is doing exactly the same thing the triangle(method issumming all the columns for some number passed as an argument so why not use the triangle(method itselfinstead of some other methodthat would look like thisint triangle(int nreturnn triangle( - )/(incomplete versionyou may be amazed that method can call itselfbut why shouldn' it be able toa method call is (among other thingsa transfer of control to the start of the method this transfer of control can take place from within the method as well as from outside passing the buck all these approaches may seem like passing the buck someone tells me to find the th triangular number know this is plus the th triangular numberso call harry and ask him to find the th triangular number when hear back from himi'll add to whatever he tells meand that will be the answer |
22,768 | harry knows the th triangular number is plus the th triangular numberso he calls sally and asks her to find the th triangular number this process continues with each person passing the buck to another one where does this buck-passing endsomeone at some point must be able to figure out an answer that doesn' involve asking another person to help if this didn' happenthere would be an infinite chain of people asking other people questions-- sort of arithmetic ponzi scheme that would never end in the case of triangle()this would mean the method calling itself over and over in an infinite series that would eventually crash the program the buck stops here to prevent an infinite regressthe person who is asked to find the first triangular number of the serieswhen is must knowwithout asking anyone elsethat the answer is there are no smaller numbers to ask anyone aboutthere' nothing left to add to anything elseso the buck stops there we can express this by adding condition to the triangle(methodint triangle(int nif( == return else returnn triangle( - )the condition that leads to recursive method returning without making another recursive call is referred to as the base case it' critical that every recursive method have base case to prevent infinite recursion and the consequent demise of the program the triangle java program does recursion actually workif you run the triangle java programyou'll see that it does enter value for the term numbernand the program will display the value of the corresponding triangular number listing shows the triangle java program listing the triangle java program /triangle java /evaluates triangular numbers /to run this programc>java triangleapp import java io */for / /////////////////////////////////////////////////////////////// |
22,769 | listing recursion continued class triangleapp static int thenumberpublic static void main(string[argsthrows ioexception system out print("enter number")thenumber getint()int theanswer triangle(thenumber)system out println("triangle="+theanswer)/end main(//public static int triangle(int nif( == return else returnn triangle( - )//public static string getstring(throws ioexception inputstreamreader isr new inputstreamreader(system in)bufferedreader br new bufferedreader(isr)string br readline()return //public static int getint(throws ioexception string getstring()return integer parseint( )///end class triangleapp ///////////////////////////////////////////////////////////////the main(routine prompts the user for value for ncalls triangle()and displays the return value the triangle(method calls itself repeatedly to do all the work |
22,770 | here' some sample outputenter number triangle incidentallyif you're skeptical of the results returned from triangle()you can check them by using the following formulanth triangular number ( + )/ what' really happeninglet' modify the triangle(method to provide an insight into what' happening when it executes we'll insert some output statements to keep track of the arguments and return valuespublic static int triangle(int nsystem out println("enteringn= )if( == system out println("returning ")return else int temp triangle( - )system out println("returning temp)return temphere' the interaction when this method is substituted for the earlier triangle(method and the user enters enter number enteringn= enteringn= enteringn= enteringn= enteringn= returning returning returning |
22,771 | recursion returning returning triangle each time the triangle(method calls itselfits argumentwhich starts at is reduced by the method plunges down into itself again and again until its argument is reduced to then it returns this triggers an entire series of returns the method rises back upphoenix-likeout of the discarded versions of itself each time it returnsit adds the value of it was called with to the return value from the method it called the return values recapitulate the series of triangular numbersuntil the answer is returned to main(figure shows how each invocation of the triangle(method can be imagined as being "insidethe previous one called with = version = version = version = version = version = returns adds returns adds returns adds returns adds returns returns figure the recursive triangle(method |
22,772 | notice thatjust before the innermost version returns there are actually five different incarnations of triangle(in existence at the same time the outer one was passed the argument the inner one was passed the argument characteristics of recursive methods although it' shortthe triangle(method possesses the key features common to all recursive routinesit calls itself when it calls itselfit does so to solve smaller problem there' some version of the problem that is simple enough that the routine can solve itand returnwithout calling itself in each successive call of recursive method to itselfthe argument becomes smaller (or perhaps range described by multiple arguments becomes smaller)reflecting the fact that the problem has become "smalleror easier when the argument or range reaches certain minimum sizea condition is triggered and the method returns without calling itself is recursion efficientcalling method involves certain overhead control must be transferred from the location of the call to the beginning of the method in additionthe arguments to the method and the address to which the method should return must be pushed onto an internal stack so that the method can access the argument values and know where to return in the case of the triangle(methodit' probable thatas result of this overheadthe while loop approach executes more quickly than the recursive approach the penalty may not be significantbut if there are large number of method calls as result of recursive methodit might be desirable to eliminate the recursion we'll talk about this issue more at the end of this another inefficiency is that memory is used to store all the intermediate arguments and return values on the system' internal stack this may cause problems if there is large amount of dataleading to stack overflow recursion is usually used because it simplifies problem conceptuallynot because it' inherently more efficient mathematical induction recursion is the programming equivalent of mathematical induction mathematical induction is way of defining something in terms of itself (the term is also used to |
22,773 | recursion describe related approach to proving theorems using inductionwe could define the triangular numbers mathematically by saying tri( if tri(nn tri( - if defining something in terms of itself may seem circularbut in fact it' perfectly valid (provided there' base casefactorials factorials are similar in concept to triangular numbersexcept that multiplication is used instead of addition the triangular number corresponding to is found by adding to the triangular number of - while the factorial of is found by multiplying by the factorial of - that isthe fifth triangular number is + + + + while the factorial of is * * * * which equals table shows the factorials of the first numbers table factorials number calculation factorial by definition * * * * , , , , , the factorial of is defined to be factorial numbers grow large very rapidlyas you can see recursive method similar to triangle(can be used to calculate factorials it looks like thisint factorial(int nif( == return else return ( factorial( - ) |
22,774 | there are only two differences between factorial(and triangle(firstfactorial(uses instead of in the expression factorial( - secondthe base condition occurs when is not here' some sample interaction when this method is used in program similar to triangle javaenter number factorial = figure shows how the various incarnations of factorial(call themselves when initially entered with = called with = version = version = version = version = version = return multiply by return multiply by return multiply by return multiply by return returns figure the recursive factorial(method calculating factorials is the classic demonstration of recursionalthough factorials aren' as easy to visualize as triangular numbers |
22,775 | recursion various other numerological entities lend themselves to calculation using recursion in similar waysuch as finding the greatest common denominator of two numbers (which is used to reduce fraction to lowest terms)raising number to powerand so on againwhile these calculations are interesting for demonstrating recursionthey probably wouldn' be used in practice because loop-based approach is more efficient anagrams here' different kind of situation in which recursion provides neat solution to problem permutation is an arrangement of things in definite order suppose you want to list all the anagrams of specified word--that isall possible permutations (whether they make real english word or notthat can be made from the letters of the original word we'll call this anagramming word anagramming catfor examplewould produce cat cta atc act tca tac try anagramming some words yourself you'll find that the number of possibilities is the factorial of the number of letters for letters there are possible wordsfor letters there are wordsfor letters and so on (this assumes that all letters are distinctif there are multiple instances of the same letterthere will be fewer possible words how would you write program to anagram wordhere' one approach assume the word has letters anagram the rightmost - letters rotate all letters repeat these steps times to rotate the word means to shift all the letters one position leftexcept for the leftmost letterwhich "rotatesback to the rightas shown in figure |
22,776 | temp word figure rotating word rotating the word times gives each letter chance to begin the word while the selected letter occupies this first positionall the other letters are then anagrammed (arranged in every possible positionfor catwhich has only three lettersrotating the remaining two letters simply switches them the sequence is shown in table table anagramming the word cat word display wordfirst letter remaining letters action cat yes yes no yes yes at ta at tc ct rotate at rotate ta rotate cat rotate tc rotate ct no yes yes no no tc ca ac ca at cta cat atc act atc tca tac tca cat rotate atc rotate ca rotate ac rotate tca done notice that we must rotate back to the starting point with two letters before performing three-letter rotation this leads to sequences like catctacat the redundant sequences aren' displayed how do we anagram the rightmost - lettersby calling ourselves the recursive doanagram(method takes the size of the word to be anagrammed as its only parameter this word is understood to be the rightmost letters of the complete word each |
22,777 | recursion time doanagram(calls itselfit does so with word one letter smaller than beforeas shown in figure called with word cat word cat word at word rotate at display cat word rotate ta display cta rotate cat atc word tc word rotate tc display atc word rotate ct display act rotate atc tca word ca word rotate ca display tca word rotate ac display tac rotate tca cat figure the recursive doanagram(method the base case occurs when the size of the word to be anagrammed is only one letter there' no way to rearrange one letterso the method returns immediately otherwiseit anagrams all but the first letter of the word it was given and then rotates the entire word these two actions are performed timeswhere is the size of the word here' the recursive routine doanagram() |
22,778 | public static void doanagram(int newsizeif(newsize = /if too smallreturn/go no further for(int = <newsizej++/for each positiondoanagram(newsize- )/anagram remaining if(newsize== /if innermostdisplayword()/display it rotate(newsize)/rotate word each time the doanagram(method calls itselfthe size of the word is one letter smallerand the starting position is one cell further to the rightas shown in figure newsize position level level level level figure newsize position newsize position newsize position smaller and smaller words listing shows the complete anagram java program the main(routine gets word from the userinserts it into character array so it can be dealt with convenientlyand then calls doanagram(listing the anagram java program /anagram java /creates anagrams /to run this programc>java anagramapp import java io *///////////////////////////////////////////////////////////////class anagramapp |
22,779 | listing recursion continued static int sizestatic int countstatic char[arrchar new char[ ]public static void main(string[argsthrows ioexception system out print("enter word")/get word string input getstring()size input length()/find its size count for(int = <sizej++/put it in array arrchar[jinput charat( )doanagram(size)/anagram it /end main(//public static void doanagram(int newsizeif(newsize = /if too smallreturn/go no further for(int = <newsizej++/for each positiondoanagram(newsize- )/anagram remaining if(newsize== /if innermostdisplayword()/display it rotate(newsize)/rotate word ///rotate left all chars from position to end public static void rotate(int newsizeint jint position size newsizechar temp arrchar[position]/save first letter for( =position+ <sizej++/shift others left arrchar[ - arrchar[ ]arrchar[ - temp/put first on right //public static void displayword( |
22,780 | listing continued if(count system out print(")if(count system out print(")system out print(++count ")for(int = <sizej++system out printarrchar[ )system out print(")system out flush()if(count% = system out println("")//public static string getstring(throws ioexception inputstreamreader isr new inputstreamreader(system in)bufferedreader br new bufferedreader(isr)string br readline()return ///end class anagramapp ///////////////////////////////////////////////////////////////the rotate(method rotates the word one position left as described earlier the displayword(method displays the entire word and adds count to make it easy to see how many words have been displayed here' some sample interaction with the programenter wordcats cats cast atsc atcs tsca tsac scat scta ctsa asct tcas satc ctas astc tcsa sact csat acts tasc stca csta acst tacs stac (is it only coincidence that scat is an anagram of cats?you can use the program to anagram five-letter or even six-letter words howeverbecause the factorial of is anagramming such long sequences may generate more words than you want to know about |
22,781 | recursion recursive binary search remember the binary search we discussed in "arrays"we wanted to find given cell in an ordered array using the fewest number of comparisons the solution was to divide the array in halfsee which half the desired cell lay individe that half in half againand so on here' what the original find(method looked like//public int find(long searchkeyint lowerbound int upperbound nelems- int curinwhile(truecurin (lowerbound upperbound if( [curin]==searchkeyreturn curin/found it else if(lowerbound upperboundreturn nelems/can' find it else /divide range if( [curinsearchkeylowerbound curin /it' in upper half else upperbound curin /it' in lower half /end else divide range /end while /end find(/you might want to reread the section on binary searches in ordered arrays in which describes how this method works alsorun the ordered workshop applet from that if you want to see binary search in action we can transform this loop-based method into recursive method quite easily in the loop-based methodwe change lowerbound or upperbound to specify new range and then cycle through the loop again each time through the loop we divide the range (roughlyin half recursion replaces the loop in the recursive approachinstead of changing lowerbound or upperboundwe call find(again with the new values of lowerbound or upperbound as arguments the loop disappearsand its place is taken by the recursive calls here' how that looks |
22,782 | private int recfind(long searchkeyint lowerboundint upperboundint curincurin (lowerbound upperbound if( [curin]==searchkeyreturn curin/found it else if(lowerbound upperboundreturn nelems/can' find it else /divide range if( [curinsearchkey/it' in upper half return recfind(searchkeycurin+ upperbound)else /it' in lower half return recfind(searchkeylowerboundcurin- )/end else divide range /end recfind(the class userrepresented by main()may not know how many items are in the array when it calls find()and in any case shouldn' be burdened with having to know what values of upperbound and lowerbound to set initially thereforewe supply an intermediate public methodfind()which main(calls with only one argumentthe value of the search key the find(method supplies the proper initial values of lowerbound and upperbound ( and nelems- and then calls the privaterecursive method recfind(the find(method looks like thispublic int find(long searchkeyreturn recfind(searchkey nelems- )listing shows the complete listing for the binarysearch java program listing the binarysearch java program /binarysearch java /demonstrates recursive binary search /to run this programc>java binarysearchapp ///////////////////////////////////////////////////////////////class ordarray private long[ /ref to array |
22,783 | listing recursion continued private int nelems/number of data items //public ordarray(int max/constructor new long[max]/create array nelems //public int size(return nelems//public int find(long searchkeyreturn recfind(searchkey nelems- )//private int recfind(long searchkeyint lowerboundint upperboundint curincurin (lowerbound upperbound if( [curin]==searchkeyreturn curin/found it else if(lowerbound upperboundreturn nelems/can' find it else /divide range if( [curinsearchkey/it' in upper half return recfind(searchkeycurin+ upperbound)else /it' in lower half return recfind(searchkeylowerboundcurin- )/end else divide range /end recfind(//public void insert(long value/put element into array int jfor( = <nelemsj++/find where it goes if( [jvalue/(linear searchbreak |
22,784 | listing continued for(int =nelemsk>jk--/move bigger ones up [ka[ - ] [jvalue/insert it nelems++/increment size /end insert(//public void display(/displays array contents for(int = <nelemsj++/for each elementsystem out print( [ ")/display it system out println("")///end class ordarray ///////////////////////////////////////////////////////////////class binarysearchapp public static void main(string[argsint maxsize /array size ordarray arr/reference to array arr new ordarray(maxsize)/create the array arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )arr insert( )/insert items |
22,785 | listing recursion continued arr display()/display array int searchkey /search for item ifarr find(searchkey!arr size(system out println("found searchkey)else system out println("can' find searchkey)/end main(/end class binarysearchapp ///////////////////////////////////////////////////////////////in main(we insert items into the array the insert(method arranges them in sorted orderthey're then displayed finallywe use find(to try to find the item with key value of here' some sample output found in binarysearch java there are items in an array figure shows how the recfind(method in this program calls itself over and overeach time with smaller range than before when the innermost version of the method finds the desired itemwhich has the key value it returns with the index value of the itemwhich is (as can be seen in the display of ordered datathis value is then returned from each version of recfind(in turnfinallyfind(returns it to the class user the recursive binary search has the same big efficiency as the non-recursive versiono(lognit is somewhat more elegantbut may be slightly slower divide-and-conquer algorithms the recursive binary search is an example of the divide-and-conquer approach you divide the big problem into two smaller problems and solve each one separately the solution to each smaller problem is the sameyou divide it into two even smaller problems and solve them the process continues until you get to the base casewhich can be solved easilywith no further division into halves the divide-and-conquer approach is commonly used with recursionalthoughas we saw in the binary search in you can also use non-recursive approach divide-and-conquer approach usually involves method that contains two recursive calls to itselfone for each half of the problem in the binary searchthere are two such callsbut only one of them is actually executed (which one depends on the value of the key the mergesortwhich we'll encounter later in this actually executes both recursive calls (to sort two halves of an array |
22,786 | called with lowerbound= upperbound= lowerbound= upperbound= lowerbound= upperbound= lowerbound= upperbound= version version version version version lowerbound= upperbound= found it at return return return return return returns figure the recursive binarysearch(method the towers of hanoi the towers of hanoi is an ancient puzzle consisting of number of disks placed on three columnsas shown in figure the disks all have different diameters and holes in the middle so they will fit over the columns all the disks start out on column the object of the puzzle is to transfer all the disks from column to column only one disk can be moved at timeand no disk can be placed on disk that' smaller than itself |
22,787 | figure recursion the towers of hanoi there' an ancient myth that somewhere in indiain remote templemonks labor day and night to transfer golden disks from one of three diamond-studded towers to another when they are finishedthe world will end any alarm you may feelhoweverwill be dispelled when you see how long it takes to solve the puzzle for far fewer than disks the towers workshop applet start up the towers workshop applet you can attempt to solve the puzzle yourself by using the mouse to drag the topmost disk to another tower figure shows how the towers look after several moves have been made figure the towers workshop applet |
22,788 | there are three ways to use the workshop appletyou can attempt to solve the puzzle manuallyby dragging the disks from tower to tower you can repeatedly press the step button to watch the algorithm solve the puzzle at each step in the solutiona message is displayedtelling you what the algorithm is doing you can press the run button and watch the algorithm solve the puzzle with no intervention on your partthe disks zip back and forth between the posts to restart the puzzletype in the number of disks you want to usefrom to and press new twice (after the first timeyou're asked to verify that restarting is what you want to do the specified number of disks will be arranged on tower once you drag disk with the mouseyou can' use step or runyou must start over with new howeveryou can switch to manual in the middle of stepping or runningand you can switch to step when you're runningand run when you're stepping try solving the puzzle manually with small number of diskssay three or four work up to higher numbers the applet gives you the opportunity to learn intuitively how the problem is solved moving subtrees let' call the initial tree-shaped (or pyramid-shapedarrangement of disks on tower tree (this kind of tree has nothing to do with the trees that are data storage structuresdescribed elsewhere in this book as you experiment with the appletyou'll begin to notice that smaller tree-shaped stacks of disks are generated as part of the solution process let' call these smaller treescontaining fewer than the total number of diskssubtrees for exampleif you're trying to transfer four disksyou'll find that one of the intermediate steps involves subtree of three disks on tower bas shown in figure figure subtree on tower these subtrees form many times in the solution of the puzzle this happens because the creation of subtree is the only way to transfer larger disk from one tower to |
22,789 | recursion anotherall the smaller disks must be placed on an intermediate towerwhere they naturally form subtree here' rule of thumb that may help when you try to solve the puzzle manually if the subtree you're trying to move has an odd number of disksstart by moving the topmost disk directly to the tower where you want the subtree to go if you're trying to move subtree with an even number of disksstart by moving the topmost disk to the intermediate tower the recursive algorithm the solution to the towers of hanoi puzzle can be expressed recursively using the notion of subtrees suppose you want to move all the disks from source tower (call it sto destination tower (call it dyou have an intermediate tower available (call it iassume there are disks on tower here' the algorithm move the subtree consisting of the top - disks from to move the remaining (largestdisk from to move the subtree from to when you beginthe source tower is athe intermediate tower is band the destination tower is figure shows the three steps for this situation firstthe subtree consisting of disks and is moved to the intermediate tower then the largest disk is moved to tower then the subtree is moved from to of coursethis solution doesn' solve the problem of how to move the subtree consisting of disks and to tower bbecause you can' move subtree all at onceyou must move it one disk at time moving the three-disk subtree is not so easy howeverit' easier than moving four disks as it turns outmoving three disks from to the destination tower can be done with the same three steps as moving four disks that ismove the subtree consisting of the top two disks from tower to intermediate tower cthen move disk from to then move the subtree back from to how do you move subtree of two disks from to cmove the subtree consisting of only one disk ( from to this is the base casewhen you're moving only one diskyou just move itthere' nothing else to do then move the larger disk ( from to cand replace the subtree (disk on it |
22,790 | subtree move subtree to aa move bottom disk to ba move subtree to ca puzzle is solved dfigure recursive solution to towers puzzle the towers java program the towers java program solves the towers of hanoi puzzle using this recursive approach it communicates the moves by displaying themthis approach requires much less code than displaying the towers it' up to the human reading the list to actually carry out the moves the code is simplicity itself the main(routine makes single call to the recursive method dotowers(this method then calls itself recursively until the puzzle is solved in this versionshown in listing there are initially only three disksbut you can recompile the program with any number |
22,791 | listing recursion the towers java program /towers java /solves the towers of hanoi puzzle /to run this programc>java towersapp ///////////////////////////////////////////////////////////////class towersapp static int ndisks public static void main(string[argsdotowers(ndisks' '' '' ')//public static void dotowers(int topnchar fromchar interchar toif(topn== system out println("disk from from to "to)else dotowers(topn- fromtointer)/from-->inter system out println("disk topn from from to "to)dotowers(topn- interfromto)/inter-->to ///end class towersapp ///////////////////////////////////////////////////////////////remember that three disks are moved from to here' the output from the programdisk from to disk from to disk from to disk from to disk from to disk from to disk from to |
22,792 | the arguments to dotowers(are the number of disks to be movedand the source (from)intermediate (inter)and destination (totowers to be used the number of disks decreases by each time the method calls itself the sourceintermediateand destination towers also change here is the output with additional notations that show when the method is entered and when it returnsits argumentsand whether disk is moved because it' the base case ( subtree consisting of only one diskor because it' the remaining bottom disk after subtree has been movedenter ( disks) =ai=bd= enter ( disks) =ai=cd= enter ( disk) =ai=bd= base casemove disk from to return ( diskmove bottom disk from to enter ( disk) =ci=ad= base casemove disk from to return ( diskreturn ( disksmove bottom disk from to enter ( disks) =bi=ad= enter ( disk) =bi=cd= base casemove disk from to return ( diskmove bottom disk from to enter ( disk) =ai=bd= base casemove disk from to return ( diskreturn ( disksreturn ( disksif you study this output along with the source code for dotower()it should become clear exactly how the method works it' amazing that such small amount of code can solve such seemingly complicated problem mergesort our final example of recursion is the mergesort this is much more efficient sorting technique than those we saw in "simple sorting,at least in terms of speed while the bubbleinsertionand selection sorts take ( timethe mergesort is ( *lognthe graph in figure (in shows how much faster this is for exampleif (the number of items to be sortedis , then is |
22,793 | recursion , , while *logn is only , if sorting this many items required seconds with the mergesortit would take almost hours for the insertion sort the mergesort is also fairly easy to implement it' conceptually easier than quicksort and the shell shortwhich we'll encounter in the next the downside of the mergesort is that it requires an additional array in memoryequal in size to the one being sorted if your original array barely fits in memorythe mergesort won' work howeverif you have enough spaceit' good choice merging two sorted arrays the heart of the mergesort algorithm is the merging of two already-sorted arrays merging two sorted arrays and creates third arraycthat contains all the elements of and balso arranged in sorted order we'll examine the merging process firstlater we'll see how it' used in sorting imagine two sorted arrays they don' need to be the same size let' say array has elements and array has they will be merged into an array that starts with empty cells figure shows these arrays abefore merge bafter merge figure merging two arrays in the figurethe circled numbers indicate the order in which elements are transferred from and to table shows the comparisons necessary to determine which element will be copied the steps in the table correspond to the steps in the figure following each comparisonthe smaller element is copied to |
22,794 | table merging operations step comparison (if anycopy compare and compare and compare and compare and compare and compare and compare and compare and copy from to copy from to copy from to copy from to copy from to copy from to copy from to copy from to copy from to copy from to notice thatbecause is empty following step no more comparisons are necessaryall the remaining elements are simply copied from into listing shows java program that carries out the merge shown in figure and table this is not recursive programit is prelude to understanding mergesort listing the merge java program /merge java /demonstrates merging two arrays into third /to run this programc>java mergeapp ///////////////////////////////////////////////////////////////class mergeapp public static void main(string[argsint[arraya { }int[arrayb { }int[arrayc new int[ ]merge(arraya arrayb arrayc)display(arrayc )/end main(///merge and into public static void mergeint[arrayaint sizeaint[arraybint sizebint[arrayc |
22,795 | listing recursion continued int adex= bdex= cdex= while(adex sizea &bdex sizeb/neither array empty ifarraya[adexarrayb[bdexarrayc[cdex++arraya[adex++]else arrayc[cdex++arrayb[bdex++]while(adex sizeaarrayc[cdex++arraya[adex++]/arrayb is empty/but arraya isn' while(bdex sizeb/arraya is emptyarrayc[cdex++arrayb[bdex++]/but arrayb isn' /end merge(///display array public static void display(int[thearrayint sizefor(int = <sizej++system out print(thearray[ ")system out println("")///end class mergeapp ///////////////////////////////////////////////////////////////in main(the arrays arrayaarrayband arrayc are createdthen the merge(method is called to merge arraya and arrayb into arraycand the resulting contents of arrayc are displayed here' the output the merge(method has three while loops the first steps along both arraya and arraybcomparing elements and copying the smaller of the two into arrayc the second while loop deals with the situation when all the elements have been transferred out of arraybbut arraya still has remaining elements (this is what happens in the examplewhere and remain in arraya the loop simply copies the remaining elements from arraya into arrayc the third loop handles the similar situation when all the elements have been transferred out of arrayabut arrayb still has remaining elementsthey are copied to arrayc |
22,796 | sorting by merging the idea in the mergesort is to divide an array in halfsort each halfand then use the merge(method to merge the two halves into single sorted array how do you sort each halfthis is about recursionso you probably already know the answeryou divide the half into two quarterssort each of the quartersand merge them to make sorted half similarlyeach pair of ths is merged to make sorted quartereach pair of ths is merged to make sorted thand so on you divide the array again and again until you reach subarray with only one element this is the base caseit' assumed an array with one element is already sorted we've seen that generally something is reduced in size each time recursive method calls itselfand built back up again each time the method returns in mergesort(the range is divided in half each time this method calls itselfand each time it returns it merges two smaller ranges into larger one as mergesort(returns from finding two arrays of one element eachit merges them into sorted array of two elements each pair of resulting -element arrays is then merged into -element array this process continues with larger and larger arrays until the entire array is sorted this is easiest to see when the original array size is power of as shown in figure firstin the bottom half of the arrayrange - and range - are merged into range - of course - and - aren' really rangesthey're only one elementso they are base cases similarly - and - are merged into - then ranges - and - are merged into - in the top half of the array - and - are merged into - - and - are merged into - and - and - are merged into - finallythe top half - and the bottom half - are merged into the complete array - which is now sorted when the array size is not power of arrays of different sizes must be merged for examplefigure shows the situation when the array size is here an array of size must be merged with an array of size to form an array of size firstthe -element ranges - and - are merged into the -element range - then range - is merged with the -element range - this creates -element range - it' merged with the -element range - the process continues until the array is sorted notice that in mergesort we don' merge two separate arrays into third oneas we demonstrated in the merge java program insteadwe merge parts of single array into itself |
22,797 | recursion figure merging larger and larger arrays you may wonder where all these subarrays are located in memory in the algorithma workspace array of the same size as the original array is created the subarrays are stored in sections of the workspace array this means that subarrays in the original array are copied to appropriate places in the workspace array after each mergethe workspace array is copied back into the original array |
22,798 | figure array size not power of the mergesort workshop applet this sorting process is easier to appreciate when you see it happening before your very eyes start up the mergesort workshop applet repeatedly pressing the step |
22,799 | recursion button will execute mergesort step by step figure shows what it looks like after the first three presses figure the mergesort workshop applet the lower and upper arrows show the range currently being considered by the algorithmand the mid arrow shows the middle part of the range the range starts as the entire array and then is halved each time the mergesort(method calls itself when the range is one elementmergesort(returns immediatelythat' the base case otherwisethe two subarrays are merged the applet provides messagessuch as entering mergesort - to tell you what it' doing and the range it' operating on many steps involve the mergesort(method calling itself or returning comparisons and copies are performed only during the merge processwhen you'll see messages like merged - and - into workspace you can' see the merge happening because the workspace isn' shown howeveryou can see the result when the appropriate section of the workspace is copied back into the original (visiblearraythe bars in the specified range will appear in sorted order firstthe first two bars will be sortedthen the first three barsthen the two bars in the range - then the three bars in the range - then the six bars in the range and so oncorresponding to the sequence shown in figure eventuallyall the bars will be sorted you can cause the algorithm to run continuously by pressing the run button you can stop this process at any time by pressing stepsingle-step as many times as you wantand resume running by pressing run again as in the other sorting workshop appletspressing new resets the array with new group of unsorted barsand toggles between random and inverse arrangements the size button toggles between bars and bars |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.