17 Data Structures.

Slides:



Advertisements
Similar presentations
Lecture Stacks. A stack is a Last-In-First-Out (LIFO) or a First-In-Last-Out (FILO) abstract data type E.g. a deck of cards in which cards may be added.
Advertisements

Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
1 Chapter 24 Lists Stacks and Queues. 2 Objectives F To design list with interface and abstract class (§24.2). F To design and implement a dynamic list.
Fall 2007CS 2251 Iterators and Tree Traversals. Fall 2007CS 2252 Binary Trees In a binary tree, each node has at most two subtrees A set of nodes T is.
CS 104 Introduction to Computer Science and Graphics Problems Data Structure & Algorithms (4) Data Structures 11/18/2008 Yang Song.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 – Data Structures Outline 20.1 Introduction 20.2 Self-Referential Classes 20.3 Dynamic Memory.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L12 (Chapter 20) Lists, Stacks,
 2009 Pearson Education, Inc. All rights reserved Data Structures Many slides modified by Prof. L. Lilien (even many without an explicit message).
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
COMP 110 Introduction to Programming Mr. Joshua Stough.
Transforming Infix to Postfix
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 – Data Structures Outline 12.1Introduction.
 2006 Pearson Education, Inc. All rights reserved Data Structures.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Data Structures Trees.
Chapter 12 Data Structure Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Data Structures Outline Introduction Self-Referential Classes Dynamic Memory Allocation Linked Lists Stacks Queues Trees.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Grade 12 Computer Studies HG
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Custom Templatized Data Structures.
 2006 Pearson Education, Inc. All rights reserved Data Structures.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
 Pearson Education, Inc. All rights reserved Data Structures.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Templatized Tree.
 2007 Pearson Education, Inc. All rights reserved C Data Structures.
Dr. Salah Hammami KSU-CCIS-CS Ahmad Al-Rjoub CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science Chapter.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 22 November 17, 2009.
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 20 Lists, Stacks,
 2002 Prentice Hall, Inc. All rights reserved. Chapter 19 – Data Structures Outline 19.1 Introduction 19.2 Self-Referential Classes 19.3 Dynamic Memory.
1 Chapter 17 Object-Oriented Data Structures. 2 Objectives F To describe what a data structure is (§17.1). F To explain the limitations of arrays (§17.1).
Self-Referential Classes A Self-referential class is a class that contains a reference to an object that has the same class type. –A self-referential class.
1 Chapter 17 – Data Structures Outline Introduction Self-Referential Classes Dynamic Memory Allocation Linked Lists Stacks Queues Trees.
Programming Practice 3 - Dynamic Data Structure
Data Structures Systems Programming. Systems Programming: Data Structures 2 2 Systems Programming: 2 Data Structures  Queues –Queuing System Models –Queue.
Final Exam –Date: Aug 27 th –Time: 9:00am – 12:00pm –Location: TEL 0014.
Chapter 16 – Data Structures and Recursion. Data Structures u Built-in –Array –struct u User developed –linked list –stack –queue –tree Lesson 16.1.
Data Structures Chapter 6. Data Structure A data structure is a representation of data and the operations allowed on that data. Examples: 1.Array 2.Record.
C How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Java How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
 2003 Prentice Hall, Inc. All rights reserved Stacks Upcoming program –Create stack from list insertAtFront, removeFromFront –Software reusability.
Chapter 20 Custom Templatized Data Structures
Data Structures: Linked Lists
Data Structure By Amee Trivedi.
12 Collections Software Solutions Lewis & Loftus java 5TH EDITION
Chapter 12 – Data Structures
5.13 Recursion Recursive functions Functions that call themselves
Stacks – review A Last-In First-Out (LIFO) structure Basic Operations:
12 C Data Structures.
12 C Data Structures.
Chapter 22 Custom Generic Data Structures
Stack and Queue APURBO DATTA.
Data Structure Interview
Chapter 17 Object-Oriented Data Structures
8-1.
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Stacks – review A Last-In First-Out (LIFO) structure Basic Operations:
8-1.
Chapter 19 – Data Structures
Dynamic Data Structures and Generics
Chapter 25 – Data Structures
20.5 Stacks Upcoming program Create stack from list
Pointers & Dynamic Data Structures
Intro to OOP with Java, C. Thomas Wu By : Zanariah Idrus
Stacks, Queues, and Deques
LINEAR DATA STRUCTURES
21 Data Structures.
Presentation transcript:

17 Data Structures

Much that I bound, I could not free; Much that I freed returned to me. Lee Wilson Dodd ‘Will you walk a little faster?’ said a whiting to a snail, ‘There’s a porpoise close behind us, and he’s treading on my tail.’ Lewis Carroll There is always room at the top. Daniel Webster Push on—keep moving. Thomas Morton I’ll turn over a new leaf. Miguel de Cervantes

OBJECTIVES In this chapter you will learn: To form linked data structures using references, self-referential classes and recursion. The type-wrapper classes that enable programs to process primitive data values as objects. To use autoboxing to convert a primitive value to an object of the corresponding type-wrapper class. To use auto-unboxing to convert an object of a type-wrapper class to a primitive value. To create and manipulate dynamic data structures, such as linked lists, queues, stacks and binary trees. Various important applications of linked data structures. How to create reusable data structures with classes, inheritance and composition.

17.1   Introduction 17.2   Type-Wrapper Classes for Primitive Types 17.3   Autoboxing and Auto-Unboxing 17.4   Self-Referential Classes 17.5   Dynamic Memory Allocation 17.6   Linked Lists 17.7   Stacks 17.8   Queues 17.9   Trees 17.10   Wrap-Up

17.1 Introduction Dynamic data structures Linear data structures Linked lists Stacks Queues Binary trees

17.2 Type-Wrapper Classes for Primitive Types In package java.lang Enable programmers to manipulate primitive-type values as objects Boolean, Byte, Character, Double, Float, Integer, Long and Short

17.3 Autoboxing and Auto-Unboxing Boxing conversion Converts a value of a primitive type to an object of the corresponding type-wrapper class Unboxing conversion Converts an object of a type-wrapper class to a value of the corresponding primitive type J2SE 5.0 automatically performs these conversions Called autoboxing and auto-unboxing

17.4 Self-Referential Classes Contains an instance variable that refers to another object of the same class type That instance variable is called a link A null reference indicates that the link does not refer to another object Illustrated by a backslash in diagrams

Fig. 17.1 | Self-referential-class objects linked together.

17.5 Dynamic Memory Allocation The ability for a program to obtain more memory space at execution time to hold new nodes and to release space no longer needed Java performs automatic garbage collection of objects that are no longer referenced in a program Node nodeToAdd = new Node( 10 ); Allocates the memory to store a Node object and returns a reference to the object, which is assigned to nodeToAdd Throws an OutOfMemoryError if insufficient memory is available

17.6 Linked Lists Linked list Linear collection of nodes Self-referential-class objects connected by reference links Can contain data of any type A program typically accesses a linked list via a reference to the first node in the list A program accesses each subsequent node via the link reference stored in the previous node Are dynamic The length of a list can increase or decrease as necessary Become full only when the system has insufficient memory to satisfy dynamic storage allocation requests

Performance Tip 17.1 An array can be declared to contain more elements than the number of items expected, but this wastes memory. Linked lists provide better memory utilization in these situations. Linked lists allow the program to adapt to storage needs at runtime.

Performance Tip 17.2 Insertion into a linked list is fast—only two references have to be modified (after locating the insertion point). All existing node objects remain at their current locations in memory.

Performance Tip 17.3 Insertion and deletion in a sorted array can be time consuming—all the elements following the inserted or deleted element must be shifted appropriately.

17.6 Linked Lists (Cont.) Singly linked list Doubly linked list Each node contains one reference to the next node in the list Doubly linked list Each node contains a reference to the next node in the list and a reference to the previous node in the list java.util’s LinkedList class is a doubly linked list implementation

Performance Tip 17.4 Normally, the elements of an array are contiguous in memory. This allows immediate access to any array element, because its address can be calculated directly as its offset from the beginning of the array. Linked lists do not afford such immediate access to their elements—an element can be accessed only by traversing the list from the front (or from the back in a doubly linked list).

Fig. 17.2 | Linked list graphical representation.

Outline (1 of 6) Field data can refer to any object List.java (1 of 6) Field data can refer to any object Stores a reference to the next ListNode object in the linked list

Outline (2 of 6) References to the first and last ListNodes in a List List.java (2 of 6) References to the first and last ListNodes in a List Call one-argument constructor

Outline Initialize both references to null List.java (3 of 6)

Outline List.java (4 of 6)

Outline List.java (5 of 6) Predicate method that determines whether the list is empty

Outline Display the list’s contents (6 of 6) List.java (6 of 6) Display a message indicating that the list is empty Output a string representation of current.data Move to the next node in the list

Outline EmptyListException .java

Outline ListTest.java (1 of 3) Insert objects at the beginning of the list using method insertAtFront Insert objects at the end of the list using method insertAtBack JVM autoboxes each literal value in an Integer object

Outline Deletes objects from the front of the list using method removeFromFront ListTest.java (2 of 3) Delete objects from the end of the list using method removeFromBack Call List method print to display the current list contents Exception handler for EmptyListException

Outline ListTest.java (3 of 3)

17.6 Linked Lists (Cont.) Method insertAtFront’s steps Call isEmpty to determine whether the list is empty If the list is empty, assign firstNode and lastNode to the new ListNode that was initialized with insertItem The ListNode constructor call sets data to refer to the insertItem passed as an argument and sets reference nextNode to null If the list is not empty, set firstNode to a new ListNode object and initialize that object with insertItem and firstNode The ListNode constructor call sets data to refer to the insertItem passed as an argument and sets reference nextNode to the ListNode passed as argument, which previously was the first node

Fig. 17.6 | Graphical representation of operation insertAtFront.

17.6 Linked Lists (Cont.) Method insertAtBack’s steps Call isEmpty to determine whether the list is empty If the list is empty, assign firstNode and lastNode to the new ListNode that was initialized with insertItem The ListNode constructor call sets data to refer to the insertItem passed as an argument and sets reference nextNode to null If the list is not empty, assign to lastNode and lastNode.nextNode the reference to the new ListNode that was initialized with insertItem The ListNode constructor sets data to refer to the insertItem passed as an argument and sets reference nextNode to null

Fig. 17.7 | Graphical representation of operation insertAtBack.

17.6 Linked Lists (Cont.) Method removeFromFront’s steps Throw an EmptyListException if the list is empty Assign firstNode.data to reference removedItem If firstNode and lastNode refer to the same object, set firstNode and lastNode to null If the list has more than one node, assign the value of firstNode.nextNode to firstNode Return the removedItem reference

Fig. 17.8 | Graphical representation of operation removeFromFront.

17.6 Linked Lists (Cont.) Method removeFromBack’s steps Throws an EmptyListException if the list is empty Assign lastNode.data to removedItem If the firstNode and lastNode refer to the same object, set firstNode and lastNode to null If the list has more than one node, create the ListNode reference current and assign it firstNode “Walk the list” with current until it references the node before the last node The while loop assigns current.nextNode to current as long as current.nextNode is not lastNode

17.6 Linked Lists (Cont.) Assign current to lastNode Set current.nextNode to null Return the removedItem reference

Fig. 17.9 | Graphical representation of operation removeFromBack.

17.7 Stacks Stacks Last-in, first-out (LIFO) data structure Method push adds a new node to the top of the stack Method pop removes a node from the top of the stack and returns the data from the popped node Program execution stack Holds the return addresses of calling methods Also contains the local variables for called methods Used by the compiler to evaluate arithmetic expressions

17.7 Stacks (Cont.) Stack class that inherits from List Stack methods push, pop, isEmpty and print are performed by inherited methods insertAtFront, removeFromFront, isEmpty and print push calls insertAtFront pop calls removeFromFront isEmpty and print can be called as inherited Other List methods are also inherited Including methods that should not be in the stack class’s public interface

Outline Class StackInheritance extends class List StackInheritance .java Method push calls inherited method insertAtFront Method pop calls inherited method removeFromFront

Outline (1 of 3) Create a StackInheritenace object StackInheritance Test.java (1 of 3) Create a StackInheritenace object Push integers onto the stack

Outline Pop the objects from the stack in an infinite while loop StackInheritance Test.java (2 of 3) Implicitly call inherited method print Display the exception’s stack trace

Outline StackInheritance Test.java (3 of 3)

17.7 Stacks (Cont.) Stack class that contains a reference to a List Enables us to hide the List methods that should not be in our stack’s public interface Each stack method invoked delegates the call to the appropriate List method method push delegates to List method insertAtFront method pop delegates to List method removeFromFront method isEmpty delegates to List method isEmpty method print delegates to List method print

Outline private List reference (1 of 2) StackComposition .java (1 of 2) push method delegates call to List method insertAtFront

Outline Method pop delegates call to List method removeFromFront StackComposition .java (2 of 2) Method isEmpty delegates call to List method isEmpty Method print delegates call to List method print

17.8 Queues Queue Similar to a checkout line in a supermarket First-in, first-out (FIFO) data structure Enqueue inserts nodes at the tail (or end) Dequeue removes nodes from the head (or front) Used to support print spooling A spooler program manages the queue of printing jobs

17.8 Queues (Cont.) Queue class that contains a reference to a List Method enqueue calls List method insertAtBack Method dequeue calls List method removeFromFront Method isEmpty calls List method isEmpty Method print calls List method print

Outline An object of class List (1 of 2) Queue.java (1 of 2) Method enqueue calls List method insertAtBack

Outline Method dequeue calls List method removeFromFront (2 of 2) Queue.java (2 of 2) Method isEmpty calls List method isEmpty Method print calls List method print

Outline (1 of 3) Create a Queue object Enqueue four integers QueueTest.java (1 of 3) Create a Queue object Enqueue four integers

Outline Dequeue the objects in first-in, first-out order (2 of 3) Queue.java (2 of 3) Display the exception’s stack trace

Outline QueueTest.java (3 of 3)

17.9 Trees Trees The root node is the first node in a tree Each link refers to a child Left child is the root of the left subtree Right child is the root of the right subtree Siblings are the children of a specific node A leaf node has no children

17.9 Trees (Cont.) Binary search trees Traversing a tree Values in the left subtree are less than the value in that subtree’s parent node and values in the right subtree are greater than the value in that subtree’s parent node Traversing a tree Inorder - traverse left subtree, then process root, then traverse right subtree Preorder - process root, then traverse left subtree, then traverse right subtree Postorder - traverse left subtree, then traverse right subtree, then process root

Fig. 17.15 | Binary tree graphical representation.

Fig. 17.16 | Binary search tree containing 12 values.

Outline (1 of 5) Declare left child, node value and right child Tree.java (1 of 5) Declare left child, node value and right child

Outline Allocate a new TreeNode and assign it to reference leftNode Tree.java (2 of 5) Allocate a new TreeNode and assign it to reference rightNode

Outline TreeNode reference to the root node of the tree (3 of 5) Tree.java (3 of 5) Allocate a new TreeNode and assign it to reference root Call TreeNode method insert Call Tree helper method preorderHelper

Outline Tree.java (4 of 5) Call Tree helper method inorderHelper

Outline Call Tree helper method postorderHelper Tree.java (5 of 5)

Outline (1 of 2) Create a Tree object Insert values into tree TreeTest.java (1 of 2) Create a Tree object Insert values into tree

Outline TreeTest.java (2 of 2)

17.9 Trees (Cont.) Inorder traversal steps Binary tree sort Return immediately if the reference parameter is null Traverse the left subtree with a call to inorderHelper Process the value in the node Traverse the right subtree with a call to inorderHelper Binary tree sort The inorder traversal of a binary search tree prints the node values in ascending order

17.9 Trees (Cont.) Preorder traversal steps Return immediately if the reference parameter is null Process the value in the node Traverse the left subtree with a call to preorderHelper Traverse the right subtree with a call to preorderHelper

17.9 Trees (Cont.) Postorder traversal steps Return immediately if the reference parameter is null Traverse the left subtree with a call to postorderHelper Traverse the right subtree with a call to postorderHelper Process the value in the node

17.9 Trees (Cont.) Duplicate elimination Because duplicate values follow the same “go left” or “go right” decisions, the insertion operation eventually compares the duplicate with a same-valued node The duplicate can then be ignored Tightly packed (or balanced) trees Each level contains about twice as many elements as the previous level Finding a match or determining that no match exists among n elements requires at most log2n comparisons Level-order traversal of a binary tree Visits the nodes of the tree row by row, starting at the root node level

Fig. 17.19 | Binary search tree with seven values.