Data Structures Chapter 12 Chapter Contents Chapter Objectives
Data Structures Chapter 12
Chapter Contents Chapter Objectives 12. 1 Introductory Example: Counting Internet Addresses 12. 2 The Array. List and Linked. List Classes 12. 3 Example: A Stack Application and Class 12. 4 Example: A Queue Class 12. 5 An Introduction to Trees Part of the Picture: Data Structures 12. 6 Graphical/Internet Java: A Polygon. Sketcher Class
Chapter Objectives Ø Study the Java collection classes, Array. List and Linked. List Ø Show to build collection classes Ø Study the stack and queue structures Ø Learn about linked structures Ø linked lists and binary trees Ø Implement and use linked structures Ø Discover how collection classes are used in graphical programming
Review Arrays l An array stores a sequence of values type [] an. Array = new type [ capacity ]; l Drawback: – capacity of array fixed – must know max number of values at compile time – either the program runs out of space or wastes space l Solution: collection classes – capacity can grow and shrink as program runs
12. 1 Introductory Example: Counting Internet Addresses l Internet TCP/IP addresses provide for two names for each computer – A host name, meaningful to humans – an IP address, meaningful to computers l Problem: – network administrator needs to review file of IP addresses using a network gateway l Solution: – read file of addresses – keep track of addresses and how many times each address shows up in the file
Class Address. Counter Note source code, Figure 12. 1 l Attributes l – maximum message length – address – count l Methods – – – constructor comparison method, equals() count incrementer accessors for address, count to-string converter for output
Class Gateway. Usage. Counter l Note source code, Figure 12. 2 l Purpose – counts IP addresses using an array list l Receives name of text file from args[0] l Action: – reads IP address from file – prints listing of IP addresses and access count for each l Note use of Array. List class – can grow or shrink as needed
12. 2 The Array. List and Linked. List Classes l Collection classes provide capability to grow and shrink as needed l Categories of collection classes – Lists: store collection of items, some of which may be the same – Sets: store collection of items with no duplicates – Maps: store collections of pairs, each associates a key with an object l Note List methods, table 12. 1
Array. List Class l Implements the List using an array – by using an Object array, can store any reference type – cannot directly store primitive types – can indirectly store such values by using instances of their wrapper types l Consider the declaration: Array. List address. Sequence = new. Array. List(); Address. Seqeunce size array 0
Adding to address. Sequence l The command address. Sequence. add(an. Address. Counter); – appends an. Address. Counter object to the sequence l The Update size system then attributewill of the Array. List Address. Seqeunce size … array 10 128. 159. 4. 201 Make first element Allocate thetoarray point the Address. Counter [0] [1] [2]. . . [m-1]
Updating address. Sequence l Consider the command ((Address. Counter) address. Sequence. get(index)). increment. Count(); // assume index == 1 Cast it as an Address. Counter object Address. Seqeunce size Increment Gets this object the count attribute array [0] [1] [2]. . . 2 128. 159. 4. 2011, 1 123. 111. 222. 333, 21 [m-1]
Enlarging the Address. Sequence Array l When allocated array is full, adding another element forces replacing array with larger one – new array of n > m allocated – values from old array copied into new array – old array replaced by new one Address. Seqeunce size array [0] [1] [2]. . . [n-1] 2 128. 159. 4. 2011, 1 123. 111. 345. 444, 1 123. 111. 222. 333, 1
Array. List Drawback l Problems arise from using an array – values can be added only at back of Array. List – to insert a value and "shift" others after it requires extensive copying of values – similarly, deleting a value requires shifting l We need a slightly different structure to allow simple insertions and deletions – the Linked. List class will accomplish this
The Linked. List Class l Given Linked. List alist = new Linked. List(); . . . a. List. add(new(integer(88)); a. List. add(new(integer(77)); a. List. add(new(integer(66)); a. List head size tail 3 Resulting object shown at left 88 77 66
Linked List Containers Attributes: a. List head size tail 3 • link to first item in the list Nodes: • size of the 3 list • Contain handles • link to lasttoitem the list • link nextinnode • link to previous node 88 77 66 • link to stored object • Links to next and previous make it a doubly linked list
Variations on Linked Lists l Lists can be linked doubly as shown l Lists can also be linked in one direction only – attribute would not need link to tail – node needs forward link and pointer to data only – last item in list has link set to null l Lists can be circularly linked – last node has link to first node
Using a Linked. List l Solve the IP address counter to use Linked. List l Note source code, Figure 12. 3 – receives text file via args[0] – reads IP addresses from file – prints listing of distinct IP addresses and number of times found in file
Using a Linked. List l Given the command Linked. List address. Sequence = new Linked. List(); l Uses the Linked. List constructor to build an empty list address. Sequence head size tail 0
Adding to the Linked List l Results of command for first address. Sequence. add(an. Address. Counter); address. Sequence head size tail 0 • Successive adds • create more nodes and data values • adjust links 123. 111. 345. 444, 1
Accessing Values in a Linked List l Must use the. get method ((Address. Counter) addresss. Sequence. get(index)). increment. Count(); l. A Linked. List has no array with an index to access an element l get method must … – begin at head node – iterate through index nodes to find match – return reference of object in that node l Command then does cast and increment. Count()
Accessing Values in a Linked List l To print successive values for the output for (int i = 0; i < address. Sequence. size(); i++) System. out. println(address. Sequence. get(i)); starts at first node, iterates i times to reach desired node get(i) method determines limit of loop counter size • Note that each get(i) must pass over the same first i-1 nodes previously accessed • This is inefficient
Accessing Values in a Linked List l An alternative, more efficient access algorithm List. Iterator it = address. Sequence. list. Iterator(); while (it. has. Next()) System. out. println( it. next()); A List. Iterator is an object that iterates across the values in a list l The next() method does the following: l 1. save handle to current node's object 2. advances iterator to next node using successor attribute 3. returns handle saved in step 1, so object pointed to can be output
Inserting Nodes Anywhere in a Linked List l Recall problem with Array. List – can add only at end of the list – linked list has capability to insert nodes anywhere l We can say address. Sequence. add(n, new an. Address. Counter); Which will … – build a new node – update head and tail links if required – update node handle links to place new node to be n th item in the list – allocates memory for the data item
Choosing the Proper List Algorithm Efficiency l "Time-efficiency" is not a real-time issue – rather an issue of how many steps an algorithm requires l Linear time – time proportional to n – referred to as O(n), "order n" l Constant time – expressed as O(1)
Demonstration of Efficiency l Note sample program List. Timer, Figure 12. 4, demonstrates performance l Observations – appending to either Array. List or Linked. List structures takes negligible time – far more time-consuming to access middle value in a Linked. List than an Array. List – far more time consuming to insert values into an Array. List than a Linked. List
Conclusions on Efficiency l If problem involves many accesses to interior of a sequence – sequence should be stored in an Array. List l If problems involves many insertions, deletions not at end – sequence should be stored in Linked. List l If neither of these is the case – it doesn't matter which is used
12. 3 Example: a Stack Application and Class l Consider an algorithm which converts from a base 10 number system to another number system. l To convert from 95 ten to base eight: Use repeated division by 1 3 7 eight, taking remainders in reverse order
Need for a Stack l The remainders are generated in the opposite order that they must be output l If we were able to … – generate them – hold on to them as generated – access (display) them in the reverse order THEN we have used a stack 137 1 3 7
Stack Container l. A stack is maintained Last-In-First-Out (not unlike a stack of plates in a cafeteria) l Standard operations – is. Empty(): returns true or false – top(): returns copy of value at top of stack (without removing it) – push(v): adds a value v at the top of the stack – pop(): removes and returns value at top
Number Base Conversion Algorithm 1. 2. Create an empty stack to hold numbers Repeat following while number != 0 Calculate remainder = number % base b) Push remainder onto stack of remainders c) Replace number = number / base a) 3. Declare result as an empty String 4. While stack not empty do the following: Remove remainder from top of stack b) Convert remainder to base equivalent c) Concatenate base equivalent to result a) 5. Return result
Implementing a Stack Class l Note use of Stack class in source code, Figure 12. 6, implementation in Figure 12. 7 l Implemented with Linked. List attribute variable to store values – this is a "has-a" relationship, the Stack has a Linked. List – contrast the "is-a" relationship
Java's Stack Class l Java has a Stack class which extends the Vector class l Author notes implementation as a subclass of Vector provides inheritance of methods inappropriate for a Stack – suggests this violates rule of thumb for use of the extends – Vector contains messages not appropriate that should not be used in Stack
12. 4 Example: Building a Queue Class l In a queue, – new values are always added at the front or head of the list – values are removed from the opposite end of the list, the rear or tail l Examples of queues – checkout at supermarket – vehicles at toll booth – ticket line at movies l Queue exhibits First-In-First-Out behavior
Queues in a Computer System l When a process (program) requires a certain resource – printer – disk access on a network – characters in a keyboard buffer l Queue Manipulation Operations – is. Empty(): returns true or false – first(): returns copy of value at front – add(v): adds a new value at rear of queue – remove(): removes, returns value at front
Implementing a Queue Class l Implement value as a Linked. List attribute – insertions and deletions from either end are efficient, occur in constant O(1) time – good choice l Implement as an Array. List attribute – poor choice – adding values at one end, removing at other end require multiple shifts
Implementing a Queue Class l Build a Queue from scratch – build a linked structure to store the queue elements l Attributes required – handle for the head node – handle for tail node – integer to store number of values in the queue – use Singly. Linked. Node class, source code, Figure 12. 8
Queue Structure a. Queue my. Head my. Size my. Tail n . . . value 0 value 1 . . . valuen-1
Queue Class Methods l Constructor – set my. Head, my. Tail to null – set my. Size to zero l is. Empty() – return results of comparison my. Size == 0 l front() – return my. Head. get. Value() // unless empty
Queue Class Methods l add() – create new node, update attribute variables – if queue is empty, must also update my. Head l remove() – must check if class not empty otherwise … – save handle to first object – adjust head to refer to node – update my. Size Note source code for whole class, Figure 12. 9
12. 5 An Introduction to Trees l We seek a way to organized a linked structure so that … – elements can be searched more quickly than in a linearly linked structure – also provide for easy insertion/deletion – permit access in less than O(n) time l Recall binary search strategy – look in middle of list – keep looking in middle of subset above or below current location in list – until target value found
Visualize Binary Search 13 28 35 49 62 66 Drawn as a binary tree 49 28 13 66 35 62 80 80
Tree Terminology l A tree consists of: – – finite collection of nodes non empty tree has a root node has no incoming links every other node in the tree can be reached from the root by unique sequence of links Sibling nodes 49 28 Leaf nodes 13 Parent 66 35 62 and 80 child nodes
Applications of Trees l Genealogical tree – pictures a person's descendants and ancestors l Game trees – shows configurations possible in a game such as the Towers of Hanoi problem l Parse trees – used by compiler to check syntax and meaning of expressions such as 2 * ( 3 + 4 )
Examples of Binary Trees l Each node has at most two children l Useful in modeling processes where a test has only two possible outcomes – true or false – coin toss, heads or tails l Each unique path can be described by the sequence of outcomes l Can be applied to decision trees in expert systems of artificial intelligence
Implementing Binary Trees l Binary tree represented by multiply linked structure – each node has two links and a handle to the data – one link to left child, other to the right my. Value my. Left. Child my. Right. Child
Implementing Binary Trees l Declaration of Binary. Tree. Node class public class Binary. Tree. Node { Pointers to // … methods go here succeeding nodes // Attributes private Binary. Tree. Node my. Left. Child, my. Right. Child; private Object my. Value; } Handle to stored value
Implementing Binary Trees is only one of the attributes of a Binary. Tree class l Also need an attribute that keeps track of the number of nodes in the tree l Binary. Tree. Node public class Binary. Tree extends Object { // … methods private Binary. Tree. Node my. Root; private int my. Size; }
Visualizing a Binary. Tree a. BTree my. Root my. Size 3 46 63 17
Binary Search Trees Search Algorithm 1. Initialize a handle current. Node to the node containing the root 2. Repeatedly do the following: If target_item < current. Node. my. Value set current. Node = current. Node. left. Child If target_item > current. Node. my. Value set current. Node = current. Node. right. Child Else terminate repetition because target_item has been found
Tree Traversals A traversal is moving through the binary tree, visiting each node exactly once l for now order not important – l Traverse Algorithm Visit the root and process its contents 2. Traverse the left subtree 1. visit its root, process 2. traverse left sub-sub tree 3. traverse right sub-sub tree 3. Traverse the right subtree 1. …
Tree Traversal is Recursive If the binary tree is empty then do nothing Else L: Traverse the left subtree N: Visit the root R: Traverse the right subtree The "anchor" The inductive step
Traversal Order Three possibilities for inductive step … l Left subtree, Node, Right subtree the inorder traversal l Node, Left subtree, Right subtree the preorder traversal l Left subtree, Right subtree, Node the postorder traversal
Constructing Binary Search Trees Repeatedly insert elements into a BST that is initially empty l Descend tree, looking for place to insert the item l – Set parent. Node = current. Node – change current. Node to its left or right child – if value being inserted is not in the tree, current. Node will eventually become null and … – parent. Node will indicate the parent of a new node to contain the value
12. 6 Graphical/Internet Java: A Polygon. Sketcher l This will illustrate usage of container class to store graphical data l The program will use the mouse to draw a closed geometric figure called a polygon l The program should distinguish between – mouse clicks: connect current (x, y) to previous (x, y) with a line segment – dragging the mouse: "rubber banding" the line segment
Behavior Polygon. Sketcher Undo Clear Complete Quit
Design l To support the "repeated undo" feature – need a LIFO structure, suggests a stack l To the support the "complete" command button – need capability to access first point where user clicked mouse – this suggests not a stack l We create our own Point. List class – gives push() and pop() capabilities – also allows access to value at other end
Coding l To represent mouse-click points – int array for x-coordinates – int array for matching y-coordinates – total number of points l Note Point. List class declaration, Figure 12. 11 l Methods – push. Point() // two versions – pop. Point() // returns a point – accessor methods
The Sketch. Panel Class needs listener methods – Mouse. Listener interface listens for button events, handles the events – Mouse. Motion. Listener interface listens for mouse movements, handles them l Our sketcher will override methods … – mouse. Pressed() – mouse. Dragged() l Other methods we need: Note source code in Figure 12. 12 – erase. Last. Line() for the Undo button – erase. All. Lines() for the Clear button – complete. Polygon() for the Complete button
Polygon. Sketcher Class l Builds the GUI – including a central Sketch. Panel l Listens for mouse button clicks l When button click events happen – action. Performed() method sends appropriate messages to the Sketch. Panel l Note source code, Figure 12. 13
Part of the Picture: Data Structures l Java provides standard classes – Array. List – Linked. List l Standard classes used to solve variety of problems l Wise use of these data structures simply solutions to many problems l Attention should be given to efficiency of structure for particular task at hand
Other Data Structures interface implemented by Hash. Set and Tree. Set classes l Set interface implemented by Tree. Map and Hash. Table classes l Map l Collections class – variety of utility methods for manipulating collections
- Slides: 61