ADT: Design & Implementation. Dr. Yingwu Zhu

Similar documents
Data Structures Using C++ 2E. Chapter 5 Linked Lists

Linked List as an ADT (cont d.)

Classes and Pointers: Some Peculiarities (cont d.)

DATA STRUCTURES USING C

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push)

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Analysis of a Search Algorithm

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Linked Lists Linked Lists, Queues, and Stacks

5. A full binary tree with n leaves contains [A] n nodes. [B] log n 2 nodes. [C] 2n 1 nodes. [D] n 2 nodes.

Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards

Glossary of Object Oriented Terms

Data Structures and Data Manipulation

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering

Common Data Structures

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Linked Lists, Stacks, Queues, Deques. It s time for a chainge!

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

7.1 Our Current Model

10CS35: Data Structures Using C

Questions 1 through 25 are worth 2 points each. Choose one best answer for each.

Unordered Linked Lists

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Data Structure with C

System Software Prof. Dr. H. Mössenböck

Pointers and Linked Lists

Lecture 12 Doubly Linked Lists (with Recursion)

Variable Base Interface

G. H. RAISONI COLLEGE OF ENGG NAGPUR-16 Session DEPARTMENT CSE Semester IV SUBJECT DSPD

Data Structures, Practice Homework 2, with Solutions (not to be handed in)

Memory Allocation. Static Allocation. Dynamic Allocation. Memory Management. Dynamic Allocation. Dynamic Storage Allocation

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

Stacks. Linear data structures

BCS2B02: OOP Concepts and Data Structures Using C++

Ordered Lists and Binary Trees

ADTs,, Arrays, Linked Lists

1. Relational database accesses data in a sequential form. (Figures 7.1, 7.2)


IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Curriculum Map. Discipline: Computer Science Course: C++

Queues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

Data Structures Using C++

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

LINKED DATA STRUCTURES

Node-Based Structures Linked Lists: Implementation

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

El Dorado Union High School District Educational Services

Sequential Data Structures

WORKSPACE WEB DEVELOPMENT & OUTSOURCING TRAINING CENTER

Output: struct treenode{ int data; struct treenode *left, *right; } struct treenode *tree_ptr;

CSI33 Data Structures

PES Institute of Technology-BSC QUESTION BANK

Sequences in the C++ STL

Data Structures, Practice Homework 3, with Solutions (not to be handed in)

INTERNATIONAL JOURNAL OF PURE AND APPLIED RESEARCH IN ENGINEERING AND TECHNOLOGY

C++ Programming Language

C++FA 5.1 PRACTICE MID-TERM EXAM

Converting a Number from Decimal to Binary

recursion, O(n), linked lists 6/14

Module 2 Stacks and Queues: Abstract Data Types

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

Cpt S 223. School of EECS, WSU

The C Programming Language course syllabus associate level

QUEUES. Primitive Queue operations. enqueue (q, x): inserts item x at the rear of the queue q

Data Structures and Algorithms

Unit Write iterative and recursive C functions to find the greatest common divisor of two integers. [6]

Home Page. Data Structures. Title Page. Page 1 of 24. Go Back. Full Screen. Close. Quit

Atmiya Infotech Pvt. Ltd. Data Structure. By Ajay Raiyani. Yogidham, Kalawad Road, Rajkot. Ph : ,

Chapter 14 The Binary Search Tree

Chapter 3: Restricted Structures Page 1

TREE BASIC TERMINOLOGIES

Data Structure [Question Bank]

1.1.3 Syntax The syntax for creating a derived class is very simple. (You will wish everything else about it were so simple though.

COMPUTER SCIENCE. Paper 1 (THEORY)

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

The Tower of Hanoi. Recursion Solution. Recursive Function. Time Complexity. Recursive Thinking. Why Recursion? n! = n* (n-1)!

Data Structures. Level 6 C Module Descriptor

root node level: internal node edge leaf node Data Structures & Algorithms McQuain

Data Structures and Algorithm Analysis (CSC317) Intro/Review of Data Structures Focus on dynamic sets

STACKS,QUEUES, AND LINKED LISTS

16 Collection Classes

DATA STRUCTURE - STACK

AP Computer Science Java Mr. Clausen Program 9A, 9B

ProfBuilder: A Package for Rapidly Building Java Execution Profilers Brian F. Cooper, Han B. Lee, and Benjamin G. Zorn

Organization of Programming Languages CS320/520N. Lecture 05. Razvan C. Bunescu School of Electrical Engineering and Computer Science

Introduction to Data Structures

C++ Overloading, Constructors, Assignment operator

Stack Allocation. Run-Time Data Structures. Static Structures

Design Patterns in C++

A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION

Binary Heap Algorithms

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Application of Stacks: Postfix Expressions Calculator (cont d.)

Polymorphism. Problems with switch statement. Solution - use virtual functions (polymorphism) Polymorphism

Algorithms and Data Structures

Transcription:

ADT: Design & Implementation Dr. Yingwu Zhu

Outline Concept: ADT Demonstration of ADT s design and implementation List as an ADT (our focus) Stack & Queue as ADTs (exercises)

Abstract Data Type (ADT) ADT = data items + operations on the data Design of ADT Determine data members & operations Implementation of ADT Storage/data structures to store the data Algorithms for the operations, i.e., how to do it 3

Example: List List as an ADT 3 different implementations Static array-based Dynamic array-based Linked-list based

Properties of Lists Can have a single element Can have no elements empty! There can be lists of lists We will look at the list as an abstract data type Homogeneous Finite length Sequential elements 5

Basic Operations Construct an empty list Determine whether or not empty Insert an element into the list Delete an element from the list Traverse (iterate through) the list to Modify Output Search for a specific value Copy or save Rearrange 6

Designing a List Class Should contain at least the following function members Constructor empty() insert() delete() display() Implementation involves Choosing data structures to store data members Choosing algorithms to implement function members 7

Impl. 1: Static Array Use a static array to hold list elements Easy to manipulate arrays for implementing operations Natural fit for mapping list elements to array elements

Design What data members? What operations?

Design const int CAPACITY = 1000; //for what purpose? typedef int ElementType; //for what purpose? class List { private: int size; //# of elements ElementType array[capacity]; public: }; 10

Implementing Operations Constructor Static array allocated at compile time. No need to allocate explicitly! Empty Check if size == 0 Traverse Use a loop from 0 th element to size 1 Insert Shift elements to right of insertion point Delete Shift elements back Also adjust size up or down 11

List Class with Static Array - Problems Stuck with "one size fits all" Could be wasting space Could run out of space Better to have instantiation of specific list: specify what the capacity should be Thus we consider creating a List class with dynamically-allocated array 12

Impl. 2: Using Dynamic Arrays Allow List objects to specify varied sizes

Dynamic-Allocation for List Class Now possible to specify different sized lists cin >> maxlistsize; List alist1(maxlistsize); List alist2(500); 14

Dynamic-Allocation for List Class Changes required in data members Eliminate const declaration for CAPACITY Add data member to store capacity specified by client program Change array data member to a pointer Constructor requires considerable change Little or no changes required for empty() display() erase() insert() 15

Design typedef int ElementType; class List { private: int mysize; //# of elements int mycapacity; ElementType *myarray; public: List (int cap); }; 16

What needs to be changed? Constructor Addition of other functions to deal with dynamically allocated memory Destructor Copy constructor (won t be discussed here) Assignment operator (won t be discussed here)

Constructor Two tasks Data member initialization Dynamically allocate memory //constructor List::List(int cap) : mysize(0), mycapacity(cap) { myarray = new int[cap]; //allocate memory assert(myarray!= 0); //need #include <cassert> }

Destructor Needed! When class object goes out of scope, the pointer to the dynamically allocated memory is reclaimed automatically The dynamically allocated memory is not The destructor reclaims dynamically allocated memory (the default destructor fails here!) 19

Destructor The default destructor needs to be overrided! De-allocate memory you allocated previously; otherwise causes memory leak problem! List::~List() { } delete [] myarray;

Problems Array capacity cannot be changed during running time (execution)! Insertion & deletion are not efficient! Involve element shifting

Impl. 3: Using Linked-Lists To address the two problems faced by arraybased solutions

Review: Linked List Linked list nodes contain Data part stores an element of the list Next part stores link/pointer to next element (when no next element, null value) 23

Basic Operations Traversal Insertion Deletion

Traversal Initialize a variable ptr to point to first node Process data where ptr points 25

Traversal (cont.) set ptr = ptr->next, process ptr- >data Continue until ptr == null 26

Insertion predptr Insertion To insert 20 after 17 newptr Need address of item before point of insertion predptr points to the node containing 17 Create a new node pointed to by newptr and store 20 in it Set the next pointer of this new node equal to the next pointer in its predecessor, thus making it point to its successor. Reset the next pointer of its predecessor to point to this new node 20 27

Insertion Note: insertion also works at end of list pointer member of new node set to null Insertion at the beginning of the list predptr must be set to first pointer member of newptr set to that value first set to value of newptr Note: In all cases, no shifting of list elements is required! 28

Operations: Deletion predptr ptr Delete node containing 22 from list. Suppose ptr points to the node to be deleted predptr points to its predecessor (the 17) Do a bypass operation: Set the next pointer in the predecessor to point to the successor of the node to be deleted Deallocate the node being deleted. To free space 29

# 1 Lesson in Pointers Before operating on an pointer, first check if it is null! if (ptr) { } //do sth. meaningful

Linked Lists - Advantages Access any item as long as external link to first item maintained Insert new item without shifting Delete existing item without shifting Can expand/contract as necessary 31

Linked Lists - Disadvantages Overhead of links: used only internally, pure overhead If dynamic, must provide destructor copy constructor (but not here!) No longer have direct access to each element of the list Many sorting algorithms need direct access Binary search needs direct access Access of n th item now less efficient must go through first element, and then second, and then third, etc. 32

Linked Lists - Disadvantages List-processing algorithms that require fast access to each element cannot be done as efficiently with linked lists. Consider adding an element at the end of the list Array a[size++] = value; This is the inefficient part Linked List Get a new node; set data part = value next part = null_value If list is empty Set first to point to new node. Else Traverse list to find last node Set next part of last node to point to new node. 33

Using C++ Pointers and Classes To Implement Nodes class Node { public: DataType data; Node * next; }; Note: The definition of a Node is recursive (or self-referential) It uses the name Node in its definition The next member is defined as a pointer to a Node 34

Declaring pointers Working with Nodes or Node* ptr; typedef Node* NodePointer; NodePointer ptr; Allocate and deallocate ptr = new Node; delete ptr; Access the data and next part of node (*ptr).data and (*ptr).next or ptr->data and ptr->next 35

Working with Nodes Note data members are public class Node { public: DataType data; Node * next; }; This class declaration will be placed inside another class declaration for List (private section), p296 36

Implementing List with Linked-Lists typedef int ElementType; class List { private: class Node { public: ElementType data; Node * next; }; data is public inside class Node class Node is private inside List typedef Node * NodePointer; } 37

Design & Impl. Add data members Add member functions

#ifndef _LIST_H #define _LIST_H typedef int ElementType; class List { private: class Node { public: ElementType data; Node* next; }; typedef Node* NodePointer; private: NodePointer first; public: List(); ~List(); void insert(elementtype x); void delete(elementtype x); }; #endif Class List

Implementing Constructor Destructor Operation: insert() Operation: delete()

Exercises Implement Stack and Queue classes with different implementations.

Stack Design and Implement a Stack class 3 options Static array Dynamic array Linked list 42

Stack.h typedef int DataType; class Stack { public: Stack(); Stack(const Stack& org); void push(const DataType& v); void pop(); DataType top() const; ~Stack(); private: class Node { public: DataType data; Node* next; Node(DataType v, Node* p) : data(v), next(0) { } }; typedef Node* NodePtr; }; NodePtr mytop; 43

Queue Design and Implement a Queue class 3 options Static array Dynamic array Linked list 44

Queue.h typedef int DataType; class Queue { public: //constructor }; // member functions private: class Node { public: DataType data; Node* next; Node(DataType v, Node* p) : data(v), next(0) { } }; typedef Node* NodePtr; NodePtr myfront, myback; 45