SCHAUM'S OUTLINE OFDATA STRUCTURES WITH JAVA Second Edition JOHN The material in this eBook also appears in the print version of this Arrays Class 29 The Sequential Search Algorithm 30 The Binary Search. Data Structures with c - By Schaum series. Ar if. Loading Preview. Sorry, preview is currently unavailable. You can download the paper by clicking the button. Data Structures With c - By Schaum Series - Free ebook download as PDF File . pdf) or Data Structures and Algorithms Made Easy-Narasimha Karumanchi.
|Language:||English, Indonesian, French|
|Genre:||Business & Career|
|ePub File Size:||30.50 MB|
|PDF File Size:||9.19 MB|
|Distribution:||Free* [*Sign up for free]|
Data Structures With C - By Schaum Lipschutz - Ebook download as PDF File . pdf) or view presentation slides Data Structure Schaum Series (Chapter 4 to 9) by Gitansh Data Structures and Algorithms Made Easy-Narasimha Karumanchi . Providing Important topics YouTube links for Data Structure and Algorithms” What is Dynamic Programming Bellman-Ford Algorithm-Single Source Shortest Path | Dynamic Programming . tauhobackbuti.cf As of today we have 78,, eBooks for you to download for free. The study of data structures and algorithms is fundamental to computer into this course.
site Edition Verified download. Good Book to go with problem solving practice. It is not a book to learn in depth knowledge on Data Structures.
One person found this helpful. Paperback Verified download. On multiple occasions there was erroneous code leading to inaccurate lessons and examples, which drove me crazy during class!
I found this book in the library and so liked it that wanted to have a copy in my personal library. It is definetely not for experts. For me it was light and enjoyable reading. Are you short on time and need a book that gives you quick summaries? Are you trying to find a source that gives you concise explanations of core concepts? Don't get me wrong: It's quite comprehensive and covers a lot of topics.
It provides excellent examples and many exercises are given and solved for you. The book is written in a clear manner also. However, this is intended as a "refresher": As you can image, each topic is given 3 lines, and then an example is provided. If you decided to pick this book up because you dont want to go through your long texbtook , and you are short on time, put it back.
This isn't the right choice - this is more of a review book. I love how this book goes over in detail about what data structures mean in Java and the exercises it has to practice that understanding. Recommended for anyone who wants to do a lot of practice on the subject. The sample codes and mainly the java generic session or any session that uses generic types that teach parameterized types are very difficult to understand due to the missing symbols.
It is not only missing this symbol but the whole generic declaration in classes and in parameters type. I had to search in the internet for a tutorial on Java generic types. I am still reading this book. Theory discussions and also practices were excellent so far and I really appreciate the author and Schaum's itself to provide CS students such a great fundamental material.
Thanks much! See all 7 reviews. site Giveaway allows you to run promotional giveaways in order to create buzz, reward your audience, and attract new followers and customers.
Learn more about site Giveaway. This item: Set up a giveaway. Customers who viewed this item also viewed.
Data Structures and Algorithms in Java 2nd Edition. Robert Lafore. Thomas H. Schaum's Outline of Software Engineering. Pages with related products. See and discover other items: There's a problem loading this menu right now. Learn more about site Prime. Get fast, free shipping with site Prime. Back to top. Get to Know Us. site Payment Products. English Choose a language for shopping. site Music Stream millions of songs. site Advertising Find, attract, and engage customers. site Drive Cloud storage from site.
Alexa Actionable Analytics for the Web. Sell on site Start a Selling Account. siteGlobal Ship Orders Internationally. site Inspire Digital Educational Resources. site Rapids Fun stories for kids on the go. These are categorized as either primitive types or reference types.
Schaum's Outline sof Data Structures with Java
The eight built-in primitive types are for integers, characters, decimal numbers, and boolean values. Reference types are user-defined, and their variables must be instantiated to hold data. Arrays are reviewed in Chapter 2; interfaces are types that cannot be instantiated; enum types are defined by listing all the values that a variable of that type may have.
Classes are concrete data types that specify how their state is stored the class fields and how their instances behave the instance methods. A class is defined in a declaration statement with this syntax: A class can have six kinds of members: Fields that specify the kind of data that the objects hold. Constructors that specify how the objects are to be created. Methods that specify the operations that the objects can perform. Nested classes. Enum type definitions. Each member of a class must be specified in its own declaration statement.
The purpose of a declaration is to introduce an identifier to the compiler. It provides all the information that the compiler needs in order to compile statements that use that identifier. A field is a variable that holds data for the object.
The simplest kind of field declaration has this syntax: For example, the Point class in Example 1. Each has the modifier protected, which means that they are accessible only from within the class itself and from its extensions. A constructor is a subprogram that creates an object. The simplest kind of constructor declaration has this syntax: If it does, it is then an executable program. Otherwise, it merely defines a new type that can be used elsewhere. In addition to its three fields, this class has two constructors and four methods.
The no-arg constructor it has no arguments defined at line 6 is declared private so that it cannot be invoked from outside of its class. It is invoked at line 4 to initialize the ZERO object. This constructor uses the this keyword at line 7 to invoke the two-arg constructor, passing 0 to num and 1 to den. The two-arg constructor at line 10 is provided to the public for constructing Ratio objects with specific num and den values.
Note that, to prevent the ZERO object from being duplicated, we could have included this at line The equals method at line 15 overrides the default equals method that is defined in the Object class which all other classes extend.
Its purpose is to return true if and only if its explicit argument object represents the same thing as its implicit argument this. It returns true immediately at line 17 if the two objects are merely different names for the same object. On the other hand, it returns false at line 19 if the explicit argument is not even the right type. These tests for the two extremes are canonical and should be done first in every equals method.
If they both are passed, then we can recast the explicit argument as an object of the same type as the implicit argument Ratio so we can access its fields num and den. The toString method at line 33 also overrides the corresponding method that is defined in the Object class.
Its purpose is to return a String representation of its implicit argument. It is invoked automatically whenever a reference to an instance of the class appears in an expression where a String object is expected. Finally, the value method at line 37 returns a decimal approximation of the numerical value of the ratio. For example, at line 7 in the test program below, x. ZERO ; System. These are summarized in the following tables. Modifier Meaning abstract The class cannot be instantiated.
Table 1. If none of these is specified, then the entity has package access, which means that it can be accessed from any class in the same package. The modifier final has three different meanings, depending upon which kind of entity it modifies. If it modifies a class, final means that the class cannot be extended to a subclass.
See Chapter 9. If it modifies a field or a local variable, it means that the variable must be initialized and cannot be changed, that is, it is a constant. If it modifies a method, it means that the method cannot be overridden in any subclass.
The modifier static means that the member can be accessed only as an agent of the class itself, as opposed to being bound to a specific object instantiated from the class. For example, the format method, invoked at line 34 in the Line class in Example 1. On the other hand, the value method, invoked at line 7 in the test program is a nonstatic method.
It is bound to the object x, an instance of the Ratio class, and is accessed x. A static method is also called a class method; a nonstatic method is also called an instance method. The object to which an instance method is bound in an invocation is called its implicit argument for that invocation.
For example, the implicit argument in the invocation x. When a class A contains references to instances of a class B and controls all access to those instances, we say that A is a composition of B. For example, a University class would be a composition of Department objects.
Each Department object belongs to a unique University object, which controls access to its department. For example, a university owns a department. When a class A contains references to a class B whose instances exist and are accessible outside of A, we say that A is an aggregation of B. For example, in a university software system, a Department class would contain references to Professor objects who are members of the department, but who also exist outside the department.
In fact, a professor could be a member of two different departments. For example, a department has a professor. When a class A includes all the members of a class B, we say that A is an extension of B, and that it inherits all the properties of B.
For example, a Professor class would be an extension of a Person objects. For example, a professor is a person. Composition is indicated by a filled diamond head adjacent to the composing class, aggregation is indicated by an empty diamond head adjacent to the aggregating class, and inheritance is indicated by an empty arrow head adjacent to the extended class. Note how the Professor constructor uses the super keyword to invoke the Person constructor at line 7. The existence of a department is dependent upon the existence of its university.
Therefore, the Department class should be completely controlled and insulated by the University class. This is done by defining it to be a nested private static class at line 2. The University. Department class has two fields: It includes an add method at line 11 for adding professors to the department. The University class has two fields: It includes two add methods at lines 28 and 36 and an accessor method that returns the Set of department names at line Note that the University.
Department class is an aggregate of Professor objects. Therefore, the Professor class is defined separately from the University. Department class. INSTR ; profs. Note that Prof. Baker is a member of both departments. Adams is promoted to Professor. PROF at line Example 1. This library is part of the java. The JCF is outlined in Chapter 4. These are summarized in Table 1.
ZERO x. The purpose of the method is to indicate whether the implicit argument is less than, equal to, or greater than the explicit argument.
The indicator is the sign of the returned integer: Negative indicates that this object. To ensure that the denominators are not negative, we employ the static utility method defined at line It ensures that the denominator of its argument is not negative.
The association symbol is a dashed arrow pointing to the interface. Note that an interface rectangle has only two parts, while a class rectangle has three.
This is because interfaces have no fields. The Comparable interface is part of the java. A char cannot be used where a boolean is expected, and a Ratio object cannot be used where a Person object is expected. But there are some situations where a variable of one type can be used where another type is expected. There are several kinds of polymorphism. The simplest kind is called inclusion polymorphism.
Illustrated in Example 1. It uses the type parameter T as a place- holder for an actual type, which will be determined at run time. When the generic method is invoked at lines 4 and 6, the type String is used in place of T. When it is invoked at lines 11 and 13, the type Ratio is used. This makes the method polymorphic, capable of printing arrays of String objects and arrays of Ratio objects.
The program also uses the generic sort method that is defined in the java.
Arrays class. It requires the type parameter T to be an extension of the Comparable interface, which both the String class and our Ratio class are.
Inclusion polymorphism and parametric polymorphism are both special cases of universal polymorphism. The other general kind of polymorphism is called ad hoc polymorphism which also has two special kinds, named overloading polymorphism and coercion.
These are best illustrated with primitive types. Coercion occurs when a value of one type is implicitly converted to a value of another type when the context requires that other type.
These libraries are orgainzed into several package hierarchies, known collectively as the Application Programming Interface API. The two most common package hierarchies are the java and javax hierarchies, parts of which are shown in Figure 1. Review Questions 1. String class 1. Problems 1. Point amplitude: Real distanceTo Point: Real equals Point: Boolean magnitude: Real toString: String xCoordinate: Real yCoordinate: Real 1.
Line contains Point: Boolean equals Line: Boolean isHorizontal: Boolean isVertical: Boolean slope: String xIntercept: Real yIntercept: Circle area: Real center: Point circumference: Real contains Point: Boolean equals Circle: Boolean radius: String CHAP. Polynomial degree: Polynomial equals Point: Boolean sum Polynomial: Polynomial toString: String valueAt Real: Answers to Review Questions 1.
The implementation stage is where the computer progam code is actually written. The behavior of a class is defined by its methods. The main method must have this header: A class member that is declared protected is accessible only from its own class and subclasses extensions. A class member that is declared private is accessible only from its own class. A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type which may be void , and is invoked using the dot operator. A class method is declared static and is invoked using the class name. For example, 1. An instance method is declared without the static modifier and is invoked using the name of the object to which it is bound. Two references are equal if they refer to the same object. In the second case, s is initialized to refer to the empty String object.
With aggregation, the component elements exits outside of the collection, can be changed by other classes, and may even be components of other aggregates. For example, inheritance allows an argument of type B to be passed to a parameter of type A if B extends A. Solutions to Problems 1. The element numbers are called index numbers.
Array elements can be accessed by their index numbers using the subscript operator , as a, a, a, and so on. Arrays are widely used because they are so efficient. Arrays are objects. Arrays are created dynamically at run time. Arrays may be assigned to variables of type Object. Any method of the Object class may be invoked on an array.
An array object contains a sequence of variables. The variables are called the components or elements of the array. If the component type is T, then the array itself has type T. An array type variable holds a reference to the array object.
The component type may itself be an array type. An array element is a component whose type is not an array type. The length of an array is its number of components. Array index values must be integers in the range Variables of type short, byte, or char can be used as indexes.
Arrays can be duplicated with the Object. Arrays can be tested for equality with the Arrays. Array objects implement Cloneable and java. Property 3 follows from Property 1.
Although array types are not classes, they behave this way as extensions of the Object class. Property 7 shows that array types are not the same as class types. They are, in fact, derived types: For every class type T there is a corresponding array type T. Also, for each of the eight primitive types, the corresponding array type exists. Technically, Java allows multidimensional arrays only with primitive types. But for objects, an array of arrays is essentially the same thing.
Since arrays themselves are objects, an array of arrays is an array of objects, and some of those component objects could also be nonarrays. See Example 2. Note that a consequence of Property 13 is that changing a reference component value to null has no effect upon the length of the array; null is still a valid value of a reference component.
Line 4 defines x to have float components. Note the two different equivalent ways to declare an array: The brackets may be a suffix on the type identifier or on the array identifier.
Line 5 defines args to have 10 String components. Line 6 defines isPrime to be an array of boolean variables. Line 7 defines fib to be an array of 8 ints, initializing them to the 8 values listed. So for example, fib has the value 3, and fib has the value Line 8 defines b to be a three-dimensional array of 4 components, each of which is a twodimensional array of 10 components, each of which is a one-dimensional array of 5 component elements of type short. Line 9 defines a to be an array of five components, each of which is an array of elements of type double.
Only three of the five component arrays are allocated. Then line 10 allocates a element array of doubles to a, and line 11 assigns 3. Line 12 defines the array objects to consist of six components, each of which is itself an array. The components of the first four component arrays are elements nonarrays. But the components of the components b and a are not elements because they are also arrays.
The actual elements of the objects array include 2, 5, and 13 components of the component fib , null components of the component a , and 2. The array a defined in Example 2.
The element type of an array in Java can be a primitive type, a reference type, or an array type. The simplest, of course, are arrays of primitive type elements, such as x, isPrime, and fib in Example 2. These are arrays that can be sorted. The array b is a duplicate of a. Similarly, the array d is a duplicate of the array c, each containing three String elements. In both cases, the duplication is obtained by invoking the clone method. Since it returns a reference to an Object, it must be cast to the array type being duplicated, int or String.
The last part of the example shows that the cloned array d is indeed a separate copy of c: The name of this class is Arrays, and it is defined in the java. Arrays Class This program imports the Arrays class from the java. It also imports the static print method from Example 2.
At line 7, the call Arrays. At line 9, the Arrays. The second argument, 44, is the search target. The method returns the index 2, which is assigned to k at line 9. Line 11 verifies that 44 is indeed the value of a.
The method is invoked again at line 13, this time searching for the target The output from line 17 shows how the Arrays. It filled the eight-element array b with the argument It will return true only if the two arrays have the same element type as a and b do: The java.
Arrays class is outlined in more detail in page It is also the least efficient. It simply examines each element sequentially, starting with the first element, until it finds the key element or it reaches the end of the array. If you were looking for someone on a moving passenger train, you would use a sequential search.
Here is the sequential search algorithm: Return 1. It is implemented in Example 2. The method returns —1 when the target is not in the array: The sequential search is correct. This means that it works. The following argument is a proof of that fact. Only step 4 executes, immediately returning 1. This satisfies the postconditions: If s0 z x, then the loop terminates, step 4 executes, and 1 is returned, and that satisfies the postcondition because the single element of the sequence is not equal to x.
We want to apply the First Principle of Mathematical Induction to deduce that the loop invariant must be true on every iteration of the loop. See page That requires the verification of the invariant on the first iteration and the deduction of the invariant on iteration i from the corresponding invariant on iteration i 1.
If s0 z x, then the loop continues on to a second iteration. Thus, si z x.
This means that, on average, the running time is proportional to the number of elements in the array. So if everything else is the same, then applying the sequential search to an array twice as long will take about twice as long, on average. If x is in the sequence s, then it must be in the subsequence ss.
Let si be the middle element of ss. The binary search is correct. The loop invariant is true on the first iteration because the current subsequence is the same as the original sequence. On every other iteration, the current subsequence was defined in the preceding iteration to be the half of the previous subsequence that remained after omitting the half that did not contain x. So if x was in the original sequence, then it must be in the current subsequence.
Thus the loop invariant is true on every iteration. Since the original sequence has only a finite number of elements, the loop cannot continue indefinitely. Consequently, the algorithm terminates either by returning i from within the loop or at step 6 or step 7 where 1 is returned. Otherwise, the loop terminates when hi CHAP. This means that, on average, the running time is proportional to the logarithm of the number of elements in the array. So if everything else is the same, if it takes an average of T milliseconds to run on an array of n elements, then will take an average of 2T milliseconds to run on an array of n 2 elements.
For example, if it takes 3 ms to search 10, elements, then it should take about 6 ms to search ,, elements! Each iteration of the loop searches a subarray that is less than half as long as the subarray on the previous iteration. Thus the total number of iterations is no more than the number of times that the length n can be divided by 2. That number is lgn.
And the total running time is roughly proportional to the number of iterations that the loop makes. Review Questions 2. Problems 2. The interpolation search can be shown to run in O lglgn time. If it took 5 ms to run on an array of 1, elements, how long would you expect it to take to run on an array of 1,, elements on the same computer?
Use the following algorithm to compute and print a sieve of size Initialize p and p to be false, and all other p[i] to be true. Repeat step 3 for each i from 3 to n, incrementing by 2. If there is a prime d the square root of i that divides i, set p[i] false.
Vector object. BitSet object. Use these definitions: Write a program that tests the Goldbach conjecture for all even numbers less than Use the Primes class from Problem 2. Your first 10 lines of output should look like this: These numbers are called Fermat primes. Write a program that finds all the Fermat primes that are in the range of the int type.
Your first 5 lines of output should look like this: This particular function was of interest to mathematicians because it produces an unusual number of prime numbers.
Write a program that finds all the Babbage primes that are less than 10, Your first five lines of output should look like this: The twin primes conjecture is that there are infinitely many twin primes. Write a program that finds all the twin primes that are less than The square numbers are 1, 4, 9, 16, 25,. He believed that most of these n are also primes, now CHAP. For example, is palindromic.
Write a program that checks each of the first 10, prime numbers and prints those that are palindromic. Answers to Review Questions 2. An array element is a component that is not itself an array type. So in a two-dimensional array a, the components of a are its row arrays, and the elements of a are double variables. A Java array has only one index variable. However, since a components indexed by that variable can itself be an array with an index , the original array appears to have more than one index.
This give the programmer some control over the consequences of such a run-time error. It depends upon how close their indexes are to multiples of midpoints of subintervals. For example, if the binary search is applied in an array of 10, elements, searching for a value that is repeated at locations 0—99, the search would return the index 77 on the 7th iteration. Solutions to Problems 2.
So an array with twice as many elements would take twice as long to process: So an array with elements would take twice as long to process: So an array with 1,, elements would also take about 2 ms to process. But if you want to maintain an ordered list that allows quick insertions and deletions, you should use a linked data structure. This chapter shows how to do that. This suggests that we should keep our arrays in sorted order.
But inserting new elements in an ordered array is difficult. The main problem is that we have to shift all the larger elements forward to make room for the new element to be placed in its correct ordered position. This can be done by the insert method shown in Example 3.
The code at lines 4—7 searches the array for the correct position for x to be inserted. The arraycopy method is a static method in the System class. It is usually the most efficient way to copy elements between arrays or within a single array. Its five arguments are: Finally, x is inserted into a[i] at line 9, as shown in Figure 3.
Figure 3. So this is a 4 n operation. Deleting an element is simply the reverse of the insertion process. So deletion is also a 4 n operation. This solution requires more space a second array and makes the code a bit more complicated. But it eliminates the need to move the elements. It allows the elements to be stored at an arbitrary position in the array, using the auxiliary index array to locate them for ordered access.
The main idea is shown in Figure 3. So if we save the order of the index numbers 3, 5, 1, 4, 6 , then we can access the elements in order: 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. 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. 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.
Join Kobo & start eReading today
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. 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.ZERO ; System.
Any major revision itself would follow the same life cycle steps. The relationships among the main classes and interfaces in the JCF are summarized in Figure 4.
JUN ; System. At line 6, the "JP" and "GB" elements are swapped, and then the list is sorted at line 8. Review Questions 5. Example 1.