CS201 Slides12

Embed Size (px)

Citation preview

  • 7/29/2019 CS201 Slides12

    1/36

    Chapter 12: Data Structures

    Presentation slides for

    Java Software SolutionsFoundations of Program DesignThird Edition

    by John Lewis and William LoftusJava Software Solutions is published by Addison-Wesley

    Presentation slides are copyright 2002 by John Lewis and William Loftus. All rights reserved.Instructors using the textbook may use and modify these slides for pedagogical purposes.

  • 7/29/2019 CS201 Slides12

    2/36

    2

    Data Structures

    Now we explore some convenient techniques fororganizing and managing information Chapter 12 focuses on:

    collections Abstract Data Types (ADTs) dynamic structures and linked lists queues and stacks non-linear data structures predefined collection classes

  • 7/29/2019 CS201 Slides12

    3/36

    Collections

    A collection is an object that serves as a repository forother objects A collection usually provides services such as adding,removing, and otherwise managing the elements it

    contains Sometimes the elements in a collection are ordered,sometimes they are not Sometimes collections are homogeneous, sometimes theare heterogeneous

  • 7/29/2019 CS201 Slides12

    4/36

    4

    Abstract Data Types

    Collections can be implemented in many different ways An abstract data type (ADT) is an organized collection ofinformation and a set of operations used to manage thatinformation The set of operations defines the interface to the ADT As long as the ADT fulfills the promises of the interface, itdoesn't really matter how the ADT is implemented Objects are a perfect programming mechanism to createADTs because their internal details are encapsulated

  • 7/29/2019 CS201 Slides12

    5/36

    5

    Abstraction

    Our data structures should be abstractions That is, they should hide unneeded details We want to separatethe interface of the structure from its

    underlying implementation This helps manage complexity and makes it possible to changethe implementation without changing the interface

    What do we mean by makes it possible to change theimplementation without changing the interface?Why is changing the implementation without changing theinterface desirable?

  • 7/29/2019 CS201 Slides12

    6/36

    What about a stack?

    Is a stack an Abstract Data Type (ADT) with a collection of dataand operations that are allow on the data?How many operations can we legally perform to manipulate a stack?

    Do we care about how these operations are implemented?

    We only care about the what, not about the how!

    A set of operations defines the interface to the ADT.What are they for a stack?

    push & pop

  • 7/29/2019 CS201 Slides12

    7/36

    7

    Static vs. Dynamic Structures

    A staticdata structure has a fixed sizeThis meaning is different from the meaning of thestatic modifier (variable shared among all instances of a class)

    Arrays are static; once you define the number ofelements it can hold, the number doesnt change A dynamicdata structure grows and shrinks at execution

    time as required by its contents A dynamic data structure is implemented using links

  • 7/29/2019 CS201 Slides12

    8/36

    8

    Object References

    Recall that an object reference is a variable that storesthe address of an object A reference also can be called a pointer References often are depicted graphically:

    student

    John Smith

    40725

    3.58

  • 7/29/2019 CS201 Slides12

    9/36

    9

    References as Links

    Object references can be used to create links betweenobjects Suppose a Student class contains a reference toanotherStudent object

    John Smith

    40725

    3.57

    Jane Jones

    58821

    3.72

    Note Janes null pointer.

  • 7/29/2019 CS201 Slides12

    10/36

    10

    References as Links

    References (pointers) can be used to create a variety oflinked structures, such as a linked list:

    info

    next

    info

    next

    info

    null

    info

    next

    Figure 12.1 A linked list

    studentList

  • 7/29/2019 CS201 Slides12

    11/36

    11

    Intermediate Nodes

    The objects being stored shouldnot be concerned withthe details of the data structure in which they may bestored For example, the Student class should not have to store

    a link to the next Student object in the list Instead, we can use a separate node class with twoparts:

    1) a reference to an independent object and 2) a link to the next node in the list

    The internal representation becomes a linked list ofnodes

  • 7/29/2019 CS201 Slides12

    12/36

    Magazine Collection

    Lets explore an example of a collection ofMagazineobjects The collection is managed by theMagazineList class,which has an private inner class calledMagazineNode Because the inner classMagazineNode is private toMagazineList, theMagazineList methods can directlyaccessMagazineNode data without violating encapsulation 1st - seeMagazineRack.java(page 641) 2nd - seeMagazine.java(page 644) 3rd - seeMagazineList.java(page 642)

    http://localhost/var/www/apps/conversion/tmp/examples/chap12/Library.javahttp://localhost/var/www/apps/conversion/tmp/examples/chap12/Book.javahttp://localhost/var/www/apps/conversion/tmp/examples/chap12/BookList.javahttp://localhost/var/www/apps/conversion/tmp/examples/chap12/BookList.javahttp://localhost/var/www/apps/conversion/tmp/examples/chap12/Book.javahttp://localhost/var/www/apps/conversion/tmp/examples/chap12/Library.java
  • 7/29/2019 CS201 Slides12

    13/36

    Fig. 12.2 inserting new node into list

    A method called insert could be defined to place anode anywhere in the list, for example to keep it sortedInserting a node into the middle of a list

    listinfo

    next

    info

    next

    info

    next

    info

    null

    info

    next

    insert this new node

  • 7/29/2019 CS201 Slides12

    14/36

    Fig. 12.3 - deleting a node from a list

    A method called delete could be defined to remove anode from the listDeleting a node from a list

    listinfo

    next

    info

    next

    info

    next

    info

    null

    info

    next

    What must we be careful of when deleting a node?

    (Hint: what could we lose?)

  • 7/29/2019 CS201 Slides12

    15/36

    15

    Fig 12.4 - doubly linked list

    It may be convenient to implement as list as a doublylinked list, with next andprevious references

    A doubly linked list

    listinfo

    next

    info

    next

    info

    next

    info

    null

    info

    next

    prev prev prev prevnull

    What is contents of the first nodes prev pointer ?

    What does a doubly linked list allow ?

  • 7/29/2019 CS201 Slides12

    16/36

    16

    Fig. 12.5 - list with front & rear references

    It may be convenient to use a separate header node, with acount and references to both the front and rear of the list

    info

    next

    info

    next

    info

    null

    info

    next

    front

    rear

    count: 4list

    What will this structure allow to occur quicker

    than without rear pointer?

    header node

    list with front and rear references

  • 7/29/2019 CS201 Slides12

    17/36

    Other Dynamic List Implementations

    A linked list can be circularly linked --last node in the list points to the first node in the list

    If the linked list is doubly linked, the first node in the list alsopoints to the last node in the listDiscuss example implementing priority control of resourceallocation

    i.e., CPU time sharing via circular queue

  • 7/29/2019 CS201 Slides12

    18/36

    Dynamic Implementations

    The representation should facilitatethe intended operations and shouldmake them easy to implement.

  • 7/29/2019 CS201 Slides12

    19/36

    Classic Data Structures

    Classic linear data structures include queues and stacks Classic nonlinear data structures include trees, binary

    trees, graphs, anddigraphs

  • 7/29/2019 CS201 Slides12

    20/36

    20

    Fig. 12.6 a queue data structure

    A queue is similar to a list but adds items only to the rearof the list and removes them only from the front It is called a FIFO data structure: First-In, First-Out Analogy: a line of people at a movie ticket window

    enqueue dequeue

    first item in,

    first item out

    last item in,

    last item out

  • 7/29/2019 CS201 Slides12

    21/36

    21

    Queues

    We can define the operations for a queue enqueue - add an item to the rear of the queue dequeue (or serve) - remove an item from the front of the queue empty - returns true if the queue is empty

    As with our linked list example, by storing genericObject references, any object can be stored in thequeue

    Queues often are helpful in simulations or any situation inwhich items get backed up while awaiting processing(Jobs waiting their turn to be processed.)

  • 7/29/2019 CS201 Slides12

    22/36

    Queues

    A queue can be represented by a singly-linked list.Operationrs: enqueue add an item to reardequeue remove an item from front

    empty returns true if queue is emptyIs it more efficient if the references point from front to the rear?

    queueinfo4

    null

    info3

    next

    rear

    info2

    next

    info1

    next

    front

    queueinfo4

    next

    info3

    next

    info2

    next

    info1

    null

    rear front

    Two

    representations

    of same queue

  • 7/29/2019 CS201 Slides12

    23/36

    Queues

    A queue can be represented by an array What may happen as queue grows via enqueue with noimmediately occurring dequeues?

    0 1 2 3 4 5

  • 7/29/2019 CS201 Slides12

    24/36

    24

    Stacks

    A stack ADT is also linear, like a list or a queue Items are added and removed from only one end of astack It is therefore LIFO: Last-In, First-Out Analogies:

    a stack of plates in a cupboard a stack of bills to be paid a stack of hay bales in a barn

  • 7/29/2019 CS201 Slides12

    25/36

    25

    Fig. 12.7 stack data structure

    Stacks often are drawn vertically:

    poppush

    first item in, last item out

    last item in, first item out

  • 7/29/2019 CS201 Slides12

    26/36

    26

    Stacks

    Some stack operations: push - add an item to the top of the stack pop - remove an item from the top of the stack peek (or top) - retrieves the top item without removing it empty - returns true if the stack is empty

    A stack can be represented by a singly-linked list; it doesntmatter whether the references point from the top toward thebottom or vice versa A stack can be represented by an array, but the new itemshould be placed in the next available place in the array ratherthan at the end of the array

    (What can happen with an array implementation?)

  • 7/29/2019 CS201 Slides12

    27/36

    Stacks

    The java.util package contains a Stack class LikeArrayList operations, the Stack operationsoperate on Object references See (not during class) Decode.java(page 649) whichreverses the strings in a message. The words in the message are separated by a single

    space. The Stack class is used to push the characters ofthe word onto the stack and then pops the characters outin reverse order.

    http://localhost/var/www/apps/conversion/tmp/examples/chap12/Decode.javahttp://localhost/var/www/apps/conversion/tmp/examples/chap12/Decode.java
  • 7/29/2019 CS201 Slides12

    28/36

    Decode.java

    S

    m

    a

    r

    t

    push

    t r a m S

    pop

    S m a r t

    reverse a string1

    2

    3

    4

    5

    2

    3

    4

    51

    Decode.java reverses the strings in a message

  • 7/29/2019 CS201 Slides12

    29/36

    Fig 12.8 - Trees

    A tree is a non-linear data structure that consists of a rootnode and potentially many levels of additional nodes that forma hierarchy

    Nodes that have no children are called leaf nodes Non-root and non-leaf nodes are called internal nodes

    A tree data structureleaf nodes

    root nodeimagine an upsidedown tree internalnodes

    Tree can re resent inheritance relationshi between classes.

    Organization chart represented via

  • 7/29/2019 CS201 Slides12

    30/36

    Organization chart represented viaa tree data structure

    leaf nodes

    root nodepresidentVP VP VP VP

    mgr mgr

    mgr

    mgr

  • 7/29/2019 CS201 Slides12

    31/36

    Binary Trees

    A binary tree is defined recursively. Either it is empty (thebase case) or it consists of a root and two subtrees, eachof which is a binary tree

    Binary trees and trees typically are represented usingreferences as dynamic links, though it is possible to usefixed representations like arrays

    leaf nodes

    root node

  • 7/29/2019 CS201 Slides12

    32/36

    Fig. 12.9 - graph

    A graph is a non-linear structure (also called a network) Unlike a tree or binary tree, a graph does not have a root noprimary entry point. Any node can be connected to any other node by an edge Can have any number of edges and nodes Analogy: the highway system connecting cities on a map

    a graph data structure

  • 7/29/2019 CS201 Slides12

    33/36

    Fig. 12.10 - digraphs

    Each edge of directed graph or digraph has a specific directiondenoted by arrows. Edges with direction sometimes are called arcs Analogy #1: airline flights between airports (see below) Analogy #2: Solution to a problem (on board miles on arcs)

    a directed graph

    airline routes represented via digraph

    What else could be provided?

    A R

    B

    C

    D E

    F

    LJ

    P

    Y

    WX

    N

    S

  • 7/29/2019 CS201 Slides12

    34/36

    Graphs and Digraphs

    Both graphs and digraphs can be represented usingdynamic links or using arrays.

    As always, the representation shouldfacilitate the intended operations andmake them convenient to implement

  • 7/29/2019 CS201 Slides12

    35/36

    Collection Classes

    The Java standard library contains several classes that representcollections, often referred to as the Java Collections API.

    (APIApplication Programmer Interface) Java Collections API supports the organization and management of data. Their underlying implementation is implied in the class names such asArrayList and LinkedList Several interfaces are used to define operations on the collections, such as

    List, Set, SortedSet,Map, and SortedMapSet a collection of items with no duplicates.

    Map group of items that can be referenced by a

    key value.

  • 7/29/2019 CS201 Slides12

    36/36

    Summary

    Chapter 12 has focused on: collections Abstract Data Types (ADTs) dynamic structures and linked lists queues and stacks non-linear data structures predefined collection classes