Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 91 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
91
Dung lượng
525,72 KB
Nội dung
12.1 representing data structures An array is only one way in which a list can be represented. Arrays are limited in one sense because they have a fixed size throughout their existence. Sometimes we don’t know how big to make an array because we don’t know how much information we will store. The ArrayList class handles this by creating a larger array and copying everything over whenever necessary. This is not necessarily an efficient implementation. A dynamic data structure is implemented using links. Using ref- erences as links between objects, we can create whatever type of struc- ture is appropriate for the situation. If implemented carefully, the structure can be quite efficient to search and modify. Structures cre- ated this way are considered to be dynamic because their size is deter- mined dynamically, as they are used, and not by their declaration. dynamic structures Recall from Chapter 4 that all objects are created dynamically using the new operator. A variable used to keep track of an object is actually a reference to the object, meaning that it stores the address of the object. Recall that a declaration such as: House home = new House (“602 Greenbriar Court”); actually accomplishes two things: it declares home to be a reference to a House object, and it instantiates an object of class House. Now consider an object that contains a reference to another object of the same type. For example: class Node { int info; Node next; } Two objects of this class can be instantiated and chained together by having the next reference of one Node object refer to the other Node object. The second object’s next reference can refer to a third Node object, and so on, creating a linked list. The first node in the list could be referenced using a separate variable. The last node in the list would have a next reference that is null, indicating the end of the list. Figure 12.1 depicts this situation. For this example, the information stored in each Node class is a simple integer, but keep in mind that we could define a class to contain any amount of information of any type. 12.1 representing data structures 639 A fixed data structure has a specific size for the duration of its existence, whereas a dynamic data structure grows and shrinks as needed. key concept A dynamically linked list is managed by storing and updat- ing references to objects. key concept 640 CHAPTER 12 data structures a dynamically linked list The program in Listing 12.1 sets up a list of Magazine objects and then prints the list. The list of magazines is encapsulated inside the MagazineList class shown in Listing 12.2 and is maintained as a dynamically linked list. The MagazineList class represents the list of magazines. From outside of the class (an external view), we do not focus on how the list is implemented. We don’t know, for instance, whether the list of magazines is stored in an array or in a linked list. The MagazineList class provides a set of methods that allows the user to maintain the list of books. That set of methods, specifically add and toString, defines the operations to the MagazineList ADT. The MagazineList class uses an inner class called MagazineNode to represent a node in the linked list. Each node contains a reference to one magazine and a reference to the next node in the list. Because MagazineNode is an inner class, it is reasonable to allow the data values in the class to be public. Therefore the code in the MagazineList class refers to those data values directly. The Magazine class shown in Listing 12.3 is well encapsulated, with all data declared as private and methods provided to accomplish any updates necessary. Note that, because we use a separate class to represent a node in the list, the Magazine class itself does not need to contain a link to the next Magazine in the list. That allows the Magazine class to be free of any issues regarding its con- tainment in a list. Other methods could be included in the MagazineList ADT. For example, in addition to the add method provided, which always adds a new magazine to the end of the list, another method called insert could be defined to add a node anywhere in the list (to keep it sorted, for instance). A parameter to insert could indicate the value of the node after which the new node should be inserted. Figure 12.2 shows how the references would be updated to insert a new node. figure 12.1 A linked list list info next info next info next info next A versatile list ADT contains insert and delete operations, which can be implemented by carefully manipulating object references. key concept Another operation that would be helpful in the list ADT would be a delete method to remove a particular node. Recall from our discussion in Chapter 5 that by removing all references to an object, it becomes a candidate for garbage col- lection. Figure 12.3 shows how references would be updated to delete a node from a list. Care must be taken to accomplish the modifications to the references in the proper order to ensure that other nodes are not lost and that references continue to refer to valid, appropriate nodes in the list. 12.1 representing data structures 641 listing 12.1 //******************************************************************* // MagazineRack.java Author: Lewis/Loftus // // Driver to exercise the MagazineList collection. //******************************************************************* public class MagazineRack { // // Creates a MagazineList object, adds several magazines to the // list, then prints it. // public static void main (String[] args) { MagazineList rack = new MagazineList(); rack.add (new Magazine("Time")); rack.add (new Magazine("Woodworking Today")); rack.add (new Magazine("Communications of the ACM")); rack.add (new Magazine("House and Garden")); rack.add (new Magazine("GQ")); System.out.println (rack); } } Time Woodworking Today Communications of the ACM House and Garden GQ output 642 CHAPTER 12 data structures listing 12.2 //******************************************************************* // MagazineList.java Author: Lewis/Loftus // // Represents a collection of magazines. //******************************************************************* public class MagazineList { private MagazineNode list; // // Sets up an initially empty list of magazines. // public MagazineList() { list = null; } // // Creates a new MagazineNode object and adds it to the end of // the linked list. // public void add (Magazine mag) { MagazineNode node = new MagazineNode (mag); MagazineNode current; if (list == null) list = node; else { current = list; while (current.next != null) current = current.next; current.next = node; } } // // Returns this list of magazines as a string. // public String toString () { String result = ""; MagazineNode current = list; while (current != null) { result += current.magazine + "\n"; current = current.next; } return result; } //***************************************************************** // An inner class that represents a node in the magazine list. // The public variables are accessed by the MagazineList class. //***************************************************************** private class MagazineNode { public Magazine magazine; public MagazineNode next; // // Sets up the node // public MagazineNode (Magazine mag) { magazine = mag; next = null; } } } listing 12.2 continued 12.1 representing data structures 643 644 CHAPTER 12 data structures listing 12.3 //******************************************************************** // Magazine.java Author: Lewis/Loftus // // Represents a single magazine. //******************************************************************** public class Magazine { private String title; // // Sets up the new magazine with its title. // public Magazine (String newTitle) { title = newTitle; } // // Returns this magazine as a string. // public String toString () { return title; } } figure 12.2 Inserting a node into the middle of a list list info next info next newNode info next info next info next 12.1 representing data structures 645 other dynamic list representations You can use different list implementations, depending on the specific needs of the program you are designing. For example, in some situations it may make pro- cessing easier to implement a doubly linked list in which each node has not only a reference to the next node in the list, but also another reference to the previous node in the list. Our generic Node class might be declared as follows: class Node { int info; Node next, prev; } Figure 12.4 shows a doubly linked list. Note that, like a single linked list, the next reference of the last node is null. Similarly, the previous node of the first node is null since there is no node that comes before the first one. This type of structure makes it easy to move back and forth between nodes in the list, but requires more effort to set up and modify. figure 12.3 Deleting a node from a list list info next info next info next info next Many variations on the imple- mentation of dynamic linked lists exist. key concept figure 12.4 A doubly linked list list info next prev prev prev prev info next info next info next Another implementation of a linked list could include a header node for the list that has a reference to the front of the list and another reference to the rear of the list. A rear reference makes it easier to add new nodes to the end of the list. The header node could contain other information, such as a count of the number of nodes currently in the list. The declaration of the header node would be similar to the following: class ListHeader { int count; Node front, rear; } Note that the header node is not of the same class as the Node class to which it refers. Figure 12.5 depicts a linked list that is implemented using a header node. Still other linked list implementations can be created. For instance, the use of a header can be combined with a doubly linked list, or the list can be maintained in sorted order. The implementation should cater to the type of processing that is required. Some extra effort to maintain a more complex data structure may be worthwhile if it makes common operations on the structure more efficient. 646 CHAPTER 12 data structures figure 12.5 A list with front and rear references list count:4 front rear info next info next info next info next 12.2 classic data structures 647 12.2 classic data structures In addition to lists, some data structures have become classic in that they repre- sent important generic situations that commonly occur in computing. They can be separated into two categories. Like lists, a queue and a stack are linear data structures, meaning that the data they represent is organized in a linear fashion. Trees and graphs, on the other hand, are non-linear data structures because their data is not organized linearly. Let’s examine each of these data structures in more detail. queues A queue is similar to a list except that it has restrictions on the way you put items in and take items out. Specifically, a queue uses first-in, first- out (FIFO) processing. That is, the first item put in the list is the first item that comes out of the list. Figure 12.6 depicts the FIFO processing of a queue. Any waiting line is a queue. Think about a line of people waiting for a teller at a bank. A customer enters the queue at the back and moves forward as earlier customers are serviced. Eventually, each customer comes to the front of the queue to be processed. Note that the processing of a queue is conceptual. We may speak in terms of people moving forward until they reach the front of the queue, but the reality might be that the front of the queue moves as elements come off. That is, we are not concerned at this point with whether the queue of customers moves toward the teller, or remains stationary as the teller moves when customers are serviced. figure 12.6 A queue data structure Items go on the queue at the rear (enqueue) Items come off the queue at the front (dequeue) A queue is a linear data struc- ture that manages data in a first-in, first-out manner. key concept 648 CHAPTER 12 data structures A queue data structure typically has the following operations: ◗ enqueue—adds an item to the rear of the queue ◗ dequeue—removes an item from the front of the queue ◗ empty—returns true if the queue is empty stacks A stack is similar to a queue except that its elements go on and come off at the same end. The last item to go on a stack is the first item to come off, like a stack of plates in the cupboard or a stack of hay bales in the barn. A stack, therefore, processes information in a last-in, first- out (LIFO) manner, as shown in Fig. 12.7. A typical stack ADT contains the following operations: ◗ push—pushes an item onto the top of the stack ◗ pop—removes an item from the top of the stack ◗ peek—retrieves information from the top item of the stack without remov- ing it ◗ empty—returns true if the stack is empty The java.util package of the API contains a class called Stack that imple- ments a stack data structure. It contains methods that correspond to the standard stack operations, plus a method that searches for a particular object in the stack. figure 12.7 A stack data structure The last item to go on the stack (push) must be the first item to come off (pop) A stack is a linear data struc- ture that manages data in a last-in, first-out manner. key concept [...]... threaded, and dynamic Java API—See Application Programming Interface Java Development Kit (JDK)—A collection of software tools available free from Sun Microsystems, the creators of the Java programming language See also Software Development Kit javac—The Java command-line compiler, which translates Java source code into Java bytecode Part of the Java Development Kit javadoc—A software tool that creates... structure of a Java software system Part of the Java Development Kit javah—A software tool that generates C header and source files, used for implementing native methods Part of the Java Development Kit javap—A software tool that disassembles a Java class file, containing unreadable bytecode, into a humanreadable version Part of the Java Development Kit jdb—The Java command-line debugger Part of the Java. .. System (DNS) Software that translates an Internet address into an IP address using a domain server design (1) The plan for implementing a program, which includes a specification of the classes and objects used and an expression of the important program algorithms (2) The process of creating a program design desk check—A type of review in which a developer carefully examines a design or program to find... Java applets through links in HTML documents Part of the Java Development Kit application—(1) A generic term for any program (2) A Java program that can be run without the use of a Web browser, as opposed to a Java applet Application Programming Interface (API)—A set of classes that defines services for a programmer Not part of the language itself, but often relied on to perform even basic tasks See... device, implemented in software, on which Java bytecode is executed Bytecode, which is architecture neutral, does not run on a particular hardware platform; instead, it runs on the JVM APPENDIX A java The Java command-line interpreter, which translates and executes Java bytecode Part of the Java Development Kit Java The programming language used throughout this text to demonstrate software development... dynamic data structure—A set of objects that are linked using references, which can be modified as needed during program execution editor—A software tool that allows the user to enter and store a file of characters on a computer Often used by programmers to enter the source code of a program efficiency—The characteristic of an algorithm that specifies the required number of a particular operation in... output of a software component The test cases focus on covering the equivalence categories and boundary values of the input See also white-box testing build-and-fix approach—An approach to software development in which a program is created without any significant planning or design, then modified until it reaches some level of acceptance It is a prevalent, but unwise, approach block—A group of programming... objects of a class It can also be referenced through the class name, without instantiating any object of that class Defined in a Java program by using the static reserved word client-server model—A manner in which to construct a software design based on objects (clients) making use of the services provided by other objects (servers) coding guidelines—A series of conventions that describe how programs... set of values and operations defined by a particular base value that determines the number of digits available and the place value of each digit object—(1) The primary software construct in the object-oriented paradigm (2) An encapsulated collection of data variables and methods (3) An instance of a class object diagram—A visual representation of the objects in a program at a given point in time, often... debugger—A software tool that allows a programmer to step through an executing program and examine the value of variables at any point See also jdb decimal—The base-10 number system, which humans use in everyday life See also binary default—A Java reserved word that is used to indicate the default case of a switch statement, used if no other cases match default visibility—The level of access designated . classes that represent collections of various types. These are often referred to as the Java Collections API (Application Programmer Interface). The names of the classes in this set generally. the list of magazines when complete. 12.3 Design and implement a version of selection sort (from Chapter 6) that operates on a linked list of nodes that each contain an integer. 12.4 Design and. defined in the Java API. Let’s look at an example that uses a stack to solve a problem. The program in Listing 12.4 accepts a string of characters that represents a secret message. The program decodes