DATA STRUCTURES IN JAVA PDF
Java animations and interactive applets for data structures and algorithms. • Hyperlinks to other data Slides in Powerpoint and PDF (one-per-page) format. Data Structures in Java for the Principled Programmer. The. √. 7 Edition. ( Software release 33). Duane A. Bailey. Williams College. September many Java tutorials online . Exercise This exercise is designed to help familiarize the reader with choosing the right data structure for the right problem.
|Language:||English, Spanish, Hindi|
|Genre:||Academic & Education|
|ePub File Size:||19.84 MB|
|PDF File Size:||16.51 MB|
|Distribution:||Free* [*Regsitration Required]|
th Street, Indianapolis, Indiana Data Structures. & Algorithms in Java. Second Edition. Robert Lafore. Page 3. Data Structures and Algorithms. We have included complete Java implementations for many data structures and algorithms Slides in PowerPoint and PDF (one-per-page) format. The slides. Data Structures and Algorithms in Java. SECOND EDITION. Adam Drozdek. Australia • Canada • Mexico • Singapore • Spain • United Kingdom • United States.
Copyright by Javin Paul Powered by Blogger.
Search This Blog. Download The E-book. Okay, here goes: I fell asleep and didn't do my essay. Should be doing my essay, however I am playing hide and seek in katherswoollett new home with the girls! Yesterday, seniors participated in a college essay writing I very scared dk in total how many essays..
If you fail, don't beat yourself up about it! It's impossible to know every essay, it's just luck x i still can't believe i cranked out that comics essay twine in two days i think mostly in fiction writing but nonfic comes so easy lmao Can pandora stop playing hercules and princess and the frog?
Im trying to write an essay without getting blissfully distracted AmeliasVagenda "Bitch, just go and watch The Social Network. Yep, he got into Stanford! Darko in particular I'm sure will be able to write "War and Peace" sized essays about said recipes. Want to give a research paper at the end of the year? But making all this other bullshit a requirement along with the paper is Tweet sponsored by the essay I'm writing for class: I am really grateful for the comics aimed at kids that are really positively queer.
Bon, maintenant que j'ai lu tout internet An index array is an array whose elements are index values for another array. By storing the index numbers 3, 5, 1, 4, 6 in an index array k shown in Figure 3. The reason we wanted to allow the element to be stored in arbitrary positions in the first place was to simplify the insertion and deletion operations.
We wanted to avoid having to shift segments of a back and forth. But the solution shown in Figure 3. If we had to insert the element 50, we could put it at position a or a or any place after a, but we would then have to insert its index into the index array k between k and k to keep track of the order of the elements.
A better solution is to use the same array positions in the index array k as we are using in the data array a. Since the index array is keeping track of the correct order of the index numbers of the data elements, it can be used to do the same for the index numbers themselves.
The starting index 3 is stored in k. That begins the chain of indexes: The index 0 signals the end of the ordered sequence. The index sequence 0, 3, 5, 1, 4, 6 gives us the data elements in order: The extra variable free, shown Figure 3. The value 7 means that k and a should be used next. The implementation of an index array solves the problem of having to shift segments of array elements back and forth during deletions and insertions.
Then just follow these three steps: This improves the insert method shown in Example 3. At line 6, x is inserted in the next free location in the array a. At line 7, the index of the next location after x is stored in k[free]. At line 8, the index of x is copied into k[i], and then free is incremented to the index of the next free location.
Table of Contents
In practice, we would probably include a resize method. Their relative positions in the index array match the positions of the corresponding data elements. So we can combine them into a single array of data-address pairs, as shown in Figure 3. Fortunately, Java allows an even better solution, one that allows us to eliminate both arrays! Taking an object-oriented point of view, we see in Figure 3. Each object contains a data element and the address of the next object in the sequence.
In Java, objects are directly accessed by their addresses. Here, the arrows represent object references i. The Java runtime system does all the rest of the bookkeeping. The code is given in Example 3. Its next field is declared to have type Node. Each Node object contains a field that is a reference to a Node object.
The other field in the Node class is its data field, declared at line 2 here to be an int. Of course in general this field could be any type we want whatever type values we have to store in the list. The Node class in Example 3. Note that, since we have explicitly defined a constructor that takes at least one argument, the compiler will not implicitly define a no-argument constructor.
Therefore, since we have not explicitly defined a no-argument constructor, none will exist. That means that the only way a Node object can be created is with the one-argument constructor at line 5 ; that is, we must provide a data value for each new Node object that we create. Its data field contains the integer 22, and its next field contains a reference to another Node object not shown. Although it is common to use an arrow like this to represent an object reference, it is good to keep in mind that the actual value of the reference is the memory address of the object to which it refers.
In other programming languages, such variables are called pointers; hence their common depiction as arrows. Recall that in Java each reference variable either locates an object or is null. The value null means that the variable does not refer to any object. The memory address that is stored in a null reference variable is 0x0 the hexadecimal value 0 ; no Figure 3.
Example 3. The result is shown in Figure 3.
Note that the start variable is merely a reference to the Node object. Also note that the next reference in the Node object is null, indicated by the black dot with no arrow emanating from it. In Java, every class field that is an object reference i. In the figures that follow, each Node object is shown as a box with two parts: This simply abbreviates the versions shown in Figure 3. Continuing the code in Example 3. Now the list has two nodes, as shown in Figure 3.
Data Structures with Java
To do that, we have to assign it to the next field of the node that contains But the only node to which we have external access i. Its name is start. So we have to use the expression start. Similarly, the fourth node is added at line 4 using the expression start. That finally gives us the five-node list shown in Figure 3. The code in Example 3. Obviously, if we wanted to build a linked list of 50 nodes, this approach would be unworkable.
Since it will refer to individual nodes, it should be declared to be a Node reference, like this: Node p; And since our only access to the nodes is from the start node, we should initialize p like this: This same assignment can thus be executed as many times as is needed to advance through the linked list. But one big advange is that it is easily managed within a loop. For example, the same list can be built with the three lines of code in Example 3. Each step in the execution of this code is shown in Figure 3.
The reference variable p is analogous to an array index i: It advances through the nodes of a linked list just as i advances through the elements of an array. Consequently, it is natural to use p in a for loop, just as we would use the array index i. For example, compare Example 3. Then the for loop at lines 5—7 constructs the other four nodes.
The second for loop at lines 8—10 prints the node data in the first five lines of output. The third for loop at lines 11—13 gives the actual memory addresses of the five Node objects. When you use an object reference like p in a string expression such as System. Unless it has been overridden, the version of the toString method that is defined in the Object class will execute, as it did in the program in Example 3.
So the last five lines of output report that the five Node objects are stored at the hexadecimal memory addresses 0xc1, 0x3f5d07, 0xf4a24a, 0xcac, and 0xa These then are the actual values stored in the reference variables start, start. You can see from Figure 3.
Showing the actual memory address values instead requires more effort to see which node references which. Moreover, those memory address values are runtime dependent: They will be different on different computers, and maybe even on the same computer at different times.
One final note: When i is 1, that evaluates to 33; when i is 4, it evaluates to After the value is obtained, it is passed to the Node class constructor at line 5 of Example 3. That constructs a node with that value in its data field and null in its next field. The constructor returns a reference to the Node object. It is that reference that is assigned first to p.
lab-manual-ds-java.pdf - Lab Manual for Data Structures...
The key is that the assignments are made from right to left. So we know that p is not updated until after its next field is. So, first the next field is set to point to the new node, and then the loop control variable p is advanced to that next node. To simplify the process, we add a two-argument constructor to our Node class, as shown in Example 3. This allows us to create the node and insert it all at once.
It shows next as a reference to a Node object and x as an int with value Passing these two arguments to the constructor creates a new Node object that contains 50 and whose next field points to the same object that the given next pointer points to. The constructor then returns a reference to the new Node object, which is assigned to q.
To appreciate its simplicity, compare it with the equivalent method in Example 3. The variable p is declared at line 4 to be a reference to Node objects. It is initialized to point to the start node, which contains 22 in Figure 3. The loop control condition p. But inside the loop, at line 6, the condition will stop the loop prematurely, before p reaches any nodes that should come after the new node. This is how the list remains in ascending order: New elements are always inserted between the elements that are less than it and those that are greater than it.
On each iteration of the while loop, this assignment moves p to point to the next node in the list. The actual insertion is done by the statement at line 9.
The expression new Node x,p. The statement at line 7 assigns it to p. This changes the next pointer of the p node the node containing At that point, p. Once we understand this process, we might as well use the power of Java and write it in the single statement p. To see why that precondition is needed, look at what the method would do if x were 20 instead of In that case, the break condition at line 6 would be true on the first iteration of the while loop, leaving p pointing at the start node when the new node gets inserted at line 9.
The result, as shown in Figure 3. The problem is that we lack a node to precede the new one. This uses a little extra space, but it allows the insert method in Example 3. The other solution is to modify the insert method in Example 3. This is done in Example 3. There are two situations in which the insert should be done at the front of the list: Both conditions are handled at line 4. In the first case, we could simply reset start to a new node containing x, like this: In the second case, we also have to assign the new node to start, but we also have to connect it to the rest of the list.
But the only reference we have to the beginning of the list is start itself, so we would have to hold that reference in a temporary variable before reassigning start to the new node. Note that unlike the simpler version in Example 3. The same is true for deletion.
Like the insert method, the delete method has two main parts: It also handles the special case at the front of the list separately. Also, if the first element is greater than x, then since the list is sorted, all the elements must be greater than x, so x is not in the list.
Both of 1 2 these cases are handled first at line 5. If the first element in the list equals x, then it is deleted at line 8. This is done by returning start. If it finds one greater, then the method breaks at line 12 and returns without changing the list. If it finds an element equal to x, then it deletes it at line This is illustrated in Figure 3. A class that is a member of another class is called a nested class. This is an important example of the information hiding principle that we have applied in other contexts.
If X is any type class or interface and Y is any other type nested within X, then every member of X is accessible from Y and every member of Y is accessible from X. This is illustrated in Example 3. The Main class in Example 3. Both classes have a private int field. Main declares and initializes m at line 2; Nested declares and initializes n at line The Nested class also defines a private method f at line Outside of Nested; nested.
That instantiates the Nested class at line 5. The private field n of the Nested class is accessed at line 6, and the private method f of the Nested class is accessed at line 7. This shows that private members of a nested class are accessible from its enclosing class.
Symmetrically, the private members of the enclosing class are accessible from within its nested class, as demonstrated by line The UML symbol for the nesting of one class inside another uses a circle with a plus sign inside in place of the arrowhead, as shown in Figure 3.
Since all members of a Figure 3. Normally, a nested class should be declared static unless its instances need to access nonstatic members of its enclosing class. A nested class that is nonstatic is called an inner class. The Node class defined in Example 3. So it should be nested inside its List class.
Moreover, since nodes have no need to access List methods or fields, the Node class should be declared as a static nested class. This is done at line 12 in Example 3. A developer could change the implementation without having to modify any code outside of that class. Problems 3. Changing one list should have no effect upon the other. Note that the two lists must be completely independent of each other. Note that no new nodes are created by this method. Note that the three lists should be completely independent of each other.
Changing one list should have no effect upon the others. Answers to Review Questions 3. To find the th element, you have to move sequentially through the first 99 elements. Its main purpose is to provide a unified framework for implementing common data structures so that the resulting classes can be used in a consistent, efficient, and intuitive manner.
This chapter outlines how these types can be used. The JCF specifies four general types of collections: List, Queue, Set, and Map. These are defined as interfaces and are extended and implemented with other interfaces and classes in the java.
The relationships among the main classes and interfaces in the JCF are summarized in Figure 4. The interfaces are shown on the right in italics, and the classes that implement them are on their left. The dashed lines indicate direct implementation. Inheritance, both between classes and between interfaces is shown by solid lines. For example, the AbstractList class extends the AbstractCollection class, and the List interface extends the Collection interface.
Note that some of the class names have the prefix Abstract, which indicates that they include abstract methods that are implemented by their subclasses. A list is a sequence of elements. A queue is a first-in-first-out collection, like a waiting line. A set is an unstructured collection of distinct elements. These are more specialized types. A Deque is a doubleended queue, allowing insertions and deletions at both ends. The SortedSet and SortedMap interfaces work only with objects that can be compared, like strings.
The JCF implements the interfaces with several different data structures. The simplest structure is an indexed structure, that is, an array, which is used by the ArrayList, the ArrayDeque, the HashSet, and the HashMap classes. Other implementations use a linked structure. The specialized EnumSet and EnumMap classes use a bit string. These twelve implementations are summarized in Table 4. They are the Vector, Stack, Dictionary, and Hashtable classes.
It specifies 15 methods, as shown in the Javadoc page in Figure 4. Some of these methods are obvious: The equals and hashCode methods are inherited from the Object class and are meant to be overridden. The add method may work differently for different implementations. For collections that prohibit duplicate elements, this method should add the specified object only if it is not already an element.
For collections that allow duplicate elements, the method should add the specified CHAP. Collection interface object, possibly as a duplicate. In either case, the method should return true if and only if it changed the collection. For example, if an implement prohibits null elements, then the method should throw a NullPointerException if the argument is null.
In that case, it would implement the method like this: Note the parameter specifier: The containsAll method is to the addAll method as the contains method is to the add method. In particular, it should return true if invoked immediately after a call to the addAll method with the same Collection argument.
The iterator method returns an Iterator object that is bound to its implicit argument. Iterators are outlined on page The Collection interface specifies three optional removal methods. The remove method deletes one instance of its specified object, if it is an element. The removeAll method deletes all the elements that are equal to elements in its specified collection. The retainAll method deletes all the elements that are not equal to elements in its specified collection.
Note that the addAll , the retainAll , and the removeAll methods are equivalent to the set-theoretic union, intersection, and complement operators, respectively. These are illustrated in Figure 4.
Figure 4. The array returned by the no-argument version has type Object. The array returned by the oneargument version has the same array type as the argument. The Collection interface can be used directly as a specification for a Bag class. A bag is an unordered collection that allows duplicate elements.
Its instances represent ordinary sets of unique elements no duplicates. In fact, a set can be defined simply as a collection of unique elements. It extends the AbstractSet class. That class implements the Set interface, which extends the Collection interface. See Figure 4. The AbstractSet class implements the equals method, the hashCode method, and the removeAll method, designating the other 12 methods as abstract.
This means that the concrete EnumSet, HashSet, and TreeSet classes have their own specialized implementations of those 12 methods. The HashSet class gets its name from the fact that collections of this type maintain no order among their elements; they are all mixed up, like hash.
The isEmpty method is tested at line 4 and again at line At line 5, the collection is loaded with five elements. This is done by the static addAll method defined in the java. Collections class. Note that the order with which the five elements are printed at line 6 is different from the order with which they were added to the set. The size and contains methods are tested at lines 7—9. The add method is tested at line 11, and the remove method is tested at line At line 15, the one-argument toArray method is used to generate a String array of the same elements that are in the collection.
The for loop at lines 16—18 confirms that the array contains the same elements. Lines 20—21 create and load a second set, named g8. This is then used together with the set collection to test the retainAll , removeAll , and addAll methods at lines 23— Finally, the clear method is tested at line Specifying the element type this way causes the compiler to prevent any non-String objects from being inserted into the collection, making it type-safe.
Note that the parametrized type HashSet extends the parametrized type Set because the type HashSet extends the type Set.
The JCF uses type parameters in most of its classes and interfaces. For example, the complete Queue interface is shown in Example 4.
Whatever type that is, it must also be the type for the parameter o in the offer method at line 2 and the return type for the other four methods specified at lines 3—6.
Like a method parameter, it stands for a type that can be substituted for it. The actual type that is substituted for the type parameter is called a type argument. For example: DEC, 25 ; System. It has two type parameters: S and T. In the code at lines 14, 15, 17, 22, and 26, these two type parameters are used as place holders for actual types. Note that the expression is not used in the constructor definition at line But the construct is required when the constructor is invoked, as at line 3.
Recompile with Xlint: You can avoid that simply by specifying an element type; even Object itself, like this: This allows the type parameter E to be used in place of an actual type in the method block at line 8. Note that if we used Collection instead of Collection at line 1, then the method would only apply to collections whose element type is specified as Object.
For example, it could not be used to print a HashSet because that is not an extension of Collection. For example, if you wanted to restrict the print method in Example 4. It acts like a finger, pointing to one element at a time, much like the cursor of a text editor points to one character at a time.
And like a cursor, an iterator has the capability of moving from one element to the next and of deleting its current element. The analogy between iterators and cursors is not complete.
Most iterators cannot jump around the way cursors can. On the other hand, it is possible to have several independent iterators traversing the same collection. Moreover, it is possible to have several different iterator classes defined for the same collection class, each with its own traversal algorithms. The requirements for an iterator are specified in the java.
Iterator interface, shown in Figure 4.
Iterator interface The next method returns the current element of the collection to which the iterator is bound. Each time the next method is invoked, it advances the iterator to the next element in the collection. The hasNext method returns true unless the iterator has reached the end of its traversal. This predicate is used to determine whether the next method can be called again.
The remove method deletes the last element returned by the next method. This means that next must be called before each call to remove , designating the element to be deleted. It returns a new iterator, bound to the collection and initialized to its first element. MZ it1. BR it1. PT it1. CV The Iterator object it1 is instantiated at line 6 and returned by the iterator method.
Bound to the port collection, it visits the elements in the same order as they were printed at line 5. Note that this order is not the same as the order in which the elements were added to the collection.
Since the collection is a set, its elements have no intrinsic order. It is the iterator itself that computes the traversal sequence.
You can see from the output from line 5 that the toString method invoked implicitly by the println method uses the same traversal sequence, obviously using its own iterator to build the string. At line 11, the last next call was at line 10, which returned the MO element; so MO is deleted by remove at line Similarly, at line 14, the last next call was at line 13, which returned the GW element; so GW is deleted by remove at line These deletions are evident from the output produced by the while loop at lines 17— Notice that that loop uses the independent iterator it2 to traverse the collection.
Note that the code at lines 16—19 make a complete traversal of the collection. This is guaranteed by the instantiation of the new iterator at line 16 and the use of the hasNext method to control the loop. The last output, generated at line 21, confirms that the two iterators it1 and it2 are independent. The action of it2 had no effect on it1, which returns the CV element at line Iterators can be used in a for loop the same way: Thus, the program in Example 4.
The declared variable country takes the place of the expression it. The essential feature is that the iterator locates one element at a time in the collection. These additional 19 methods require implementing classes to maintain an ordering mechanism among their elements, allowing them to be compared for size. In Java, there are two ways for objects to be compared: Classes whose objects enjoy a natural order implement the comparable interface.
These include the wrapper classes Integer, Double, etc. User-defined orderings can be defined for a class by implementing the Comparator interface, which is part of the JCF. SortedSet interface how its two arguments are ordered: As a result, the SortedSet collection orders its elements by applying alphabetical ordering to their reversed strings.
GB engl. ZA engl. IN engl. NG The set engl is instantiated as a TreeSet of String elements at line 3 and loaded with seven elements at line 4. An eighth element is added at line 6. The outputs from lines 5 and 7 confirm that the TreeSet is maintaining its elements in their natural alphabetical order. Lines 8—13 illustrate some of the specialized methods implemented by the TreeSet class.
The headSet method returns the sorted subset of all elements that precede its argument. The subSet method returns the sorted subset of elements that begin with its first argument and precede its second argument. The tailSet method returns the sorted subset of all elements that do not precede its argument. The intrinsic difference between the HashSet and TreeSet classes is their backing data structure. The TreeSet class uses a balanced binary search tree outlined in Chapter 12 to store its elements.
The advantages and disadvantages of these two data structures are summarized in Table 4. These relative advantages and disadvantages make the choice easy: Search tree Elements are accessible in their natural order Access time is proportional to logn Table 4. In practice, the slower access time of the TreeSet class is usually not noticeable, unless the set is really large. The output from line 5 confirms that its access order matches the order in which the elements were inserted.
The output from line 9 shows that the add method inserts at the end of the linked list. In addition to the 15 methods required by the Set interface, the EnumSet class also implements the 13 additional methods specified in its Javadoc page, shown in Figure 4. Notice that each of these methods returns an EnumSet object, and every one except clone is a static method.
These are used to instantiate the sets, like this: MON, Day. SUN, Day. MAR, Month. JUN ; System. SEP, Month.
APR, Month. JUN, Month. NOV, Month. FEB ; System. Variables of that type can have only those 12 specified values or null. At line 7, the EnumSet spring is instantiated by invoking the static range method of the EnumSet class. These work as described in the Javadoc, shown in Figure 4. The addAll method is tested at line 13, producing the union of the shortMonths and spring sets.
List elements are usually numbered in sequence: The numbers are called indexes or subscripts. Unlike sets, list data structures usually allow duplicate elements.
The List interface extends the Collection interface.Note that the start variable is merely a reference to the Node object. The loop invariant is true on the first iteration because the current subsequence is the same as the original sequence. That begins the chain of indexes: The EnumMap class is defined like this: Similarly, at line 14, the last next call was at line 13, which returned the GW element; so GW is deleted by remove at line A structured approach by mark allen weiss florida international edition, florida international university of basic skills in java, data structures and chip weems.
Therefore, the Department class should be completely controlled and insulated by the University class. Consequently, it is natural to use p in a for loop, just as we would use the array index i. Answers to Review Questions 1.