11
Data AbstractionsData Abstractions
Shyh-Kang JengShyh-Kang JengDepartment of Electrical Engineering/Department of Electrical Engineering/Graduate Institute of Communication Graduate Institute of Communication
EngineeringEngineeringNational Taiwan UniversityNational Taiwan University
22
Data StructuresData Structures Conceptual organization of dataConceptual organization of data Basic data structuresBasic data structures
Homogeneous arrayHomogeneous array ListList
StackStack QueueQueue
TreeTree
33
ListList A collection of entries that appear in a A collection of entries that appear in a
sequential ordersequential order ExamplesExamples
Class enrollment listsClass enrollment lists ““things-to-do” liststhings-to-do” lists DictionariesDictionaries SentencesSentences
Appear in both static and dynamic Appear in both static and dynamic formsforms
44
StacksStacks A list in which all insertions and A list in which all insertions and
deletions are performed at the same deletions are performed at the same endend
A last-in, first-out (LIFO) structures A last-in, first-out (LIFO) structures Push and popPush and pop
C
A
B
Top
55
QueueQueue
A list in which all insertions are A list in which all insertions are performed at one end while all performed at one end while all deletions are made at the otherdeletions are made at the other
A first-in, first-out (FIFO) structureA first-in, first-out (FIFO) structure Head (front) and tail (rear)Head (front) and tail (rear)
66
Organization ChartOrganization Chart
77
File Structure of WindowsFile Structure of Windows
88
TreesTrees
99
TreesTrees NodesNodes
RootRoot Terminal (leaf)Terminal (leaf) Parent, children, siblingsParent, children, siblings
SubtreesSubtrees DepthDepth
1010
Data AbstractionData Abstraction Explores ways in which users can be Explores ways in which users can be
shielded from the details of actual data shielded from the details of actual data storage (memory cells and address) and storage (memory cells and address) and be allowed to access information as be allowed to access information as though it were stored in a more though it were stored in a more convenient form – Concept of convenient form – Concept of abstractionabstraction
The term user can be either human or a The term user can be either human or a software modulesoftware module
1111
Static vs. Dynamic Static vs. Dynamic StructuresStructures
Static structuresStatic structures Shape and size of the structure do not Shape and size of the structure do not
change over timechange over time Easier to manageEasier to manage
Dynamic structuresDynamic structures Either shape or size of the structure Either shape or size of the structure
changes over timechanges over time Must deal with adding and deleting data Must deal with adding and deleting data
entries as well as finding the memory entries as well as finding the memory space required by a growing data space required by a growing data structurestructure
1212
PointersPointers A memory cell (or perhaps a block of A memory cell (or perhaps a block of
memory cells) that contains the memory cells) that contains the address of another memory celladdress of another memory cell
ExamplesExamples Program counter as an instruction pointerProgram counter as an instruction pointer URLURL
Many programming languages include Many programming languages include pointers as a primitive data typepointers as a primitive data type Allow the declaration, allocation, and Allow the declaration, allocation, and
manipulation of pointersmanipulation of pointers Used to create dynamic data structuresUsed to create dynamic data structures
1313
Use of PointersUse of Pointers
1414
Stack and Heap SpaceStack and Heap Space
HeapStorage
StackStorage
1515
Homogeneous ArraysHomogeneous Arrays
1616
Two-Dimensional ArrayTwo-Dimensional Array
1717
Storage of a 2-D ArrayStorage of a 2-D Array Row major order vs. column major orRow major order vs. column major or
derder Finding an entry in the th row and tFinding an entry in the th row and t
h column of a h column of a -column 2-D array stor -column 2-D array stored in row major ordered in row major order
)1()1( jicx
i jc
Address polynomial
1818
Mini ReviewMini Review
Show how the array below would be Show how the array below would be arranged in main memory when arranged in main memory when stored in row major orderstored in row major order
55 33 77
44 22 88
11 99 66
1919
AnswerAnswer
5 3 7 4 2 8 1 9 65 3 7 4 2 8 1 9 6
2020
Mini ReviewMini Review Give a formula for finding the entrGive a formula for finding the entr
y in the th row and th column of y in the th row and th column of a 2-D array stored in column majoa 2-D array stored in column major orderr order
In C, C++, and Java, indices of arrays stIn C, C++, and Java, indices of arrays start at 0 rather than 1. In this case whaart at 0 rather than 1. In this case what address polynomial is used by the trat address polynomial is used by the translator to convert references of the fornslator to convert references of the form m Array[i][j]Array[i][j] into memory address? into memory address?
i j
2121
AnswersAnswers
)1()1( ijrx
jic
2222
Storing listsStoring lists
Contiguous listContiguous list = list stored in a homog = list stored in a homogeneous arrayeneous array
Linked listLinked list = list in which each node poi = list in which each node points to the next onents to the next one Head pointerHead pointer = pointer to first entry in list = pointer to first entry in list NIL pointerNIL pointer = non-pointer value used to indi = non-pointer value used to indi
cate end of listcate end of list
2323
Contiguous ListsContiguous Lists
2424
Contiguous ListContiguous List Convenient storage structure when Convenient storage structure when
implementing static listsimplementing static lists Inconvenient in dynamic casesInconvenient in dynamic cases
Delete a nameDelete a name Move entries to keep the list in the same Move entries to keep the list in the same
orderorder Add a name Add a name
Move the entire list to obtain an available Move the entire list to obtain an available block of contiguous cells large enough for the block of contiguous cells large enough for the expanded listexpanded list
2525
Linked ListLinked List
2626
Deleting an EntryDeleting an Entry
2727
Inserting an EntryInserting an Entry
2828
A Stack in MemoryA Stack in Memory
2929
Operations on QueuesOperations on Queues
3030
Circular Queues (1)Circular Queues (1)
3131
Circular Queues (2)Circular Queues (2)
3232
Mini ReviewMini Review Using paper and pencil, keep a record Using paper and pencil, keep a record
of the circular queue during the of the circular queue during the following scenario. Assume that the following scenario. Assume that the block reserved for the queue can block reserved for the queue can contain only four entries.contain only four entries. Insert entries A, B, CInsert entries A, B, C Remove two entriesRemove two entries Insert entries D, EInsert entries D, E Remove an entryRemove an entry Insert entry FInsert entry F Remove an entry Remove an entry
3333
AnswerAnswer
A B C
H T
B C
H T
C
H T
DC
HT
E DC
HT
E D
T H
E F D
T H
E F
H T
3434
Storing a binary treeStoring a binary tree Linked structureLinked structure
Each node = data cell + two child pointersEach node = data cell + two child pointers Accessed through a pointer to root nodeAccessed through a pointer to root node
Mapped to a contiguous arrayMapped to a contiguous array A[1] = root nodeA[1] = root node A[2],A[3] = children of A[1]A[2],A[3] = children of A[1] A[4],A[5],A[6],A[7] = children of A[2] and A[3]A[4],A[5],A[6],A[7] = children of A[2] and A[3] ……
3535
Binary Tree NodeBinary Tree Node
3636
Linked Storage System Linked Storage System
3737
Storage without PointersStorage without Pointers
3838
Inefficient StorageInefficient Storage
3939
Mini ReviewMini Review Draw a diagram representing how Draw a diagram representing how
the tree below appears in memory the tree below appears in memory when stored using the left and right when stored using the left and right child pointers.child pointers.
Draw another diagram showing how Draw another diagram showing how the tree would appear in contiguous the tree would appear in contiguous storage.storage.
y
x z
w
4040
AnswerAnswer
Y Z NILNIL
X NIL W NILNIL
Y X Z W
4141
Manipulating data structuresManipulating data structures
Ideally, a data structure should be Ideally, a data structure should be manipulated solely by pre-defined manipulated solely by pre-defined procedures.procedures. Example: A stack typically needs at Example: A stack typically needs at
least push and pop procedures.least push and pop procedures. The data structure along with these The data structure along with these
procedures constitutes a complete procedures constitutes a complete abstract tool.abstract tool.
4242
Printing a Linked ListPrinting a Linked List
4343
Binary Tree PackageBinary Tree Package
Search for the presence of an entrySearch for the presence of an entry Use the binary search algorithmUse the binary search algorithm
Print the list in orderPrint the list in order Insert a new entryInsert a new entry
4444
Ordered TreeOrdered Tree
4545
Search the Binary TreeSearch the Binary Tree
4646
Search Binary TreeSearch Binary Tree
4747
Printing a Binary TreePrinting a Binary Tree
4848
Mini ReviewMini Review
Draw a binary tree to store the list R, S, T,Draw a binary tree to store the list R, S, T, U, V, W, X, Y, and Z for future searching U, V, W, X, Y, and Z for future searching
4949
AnswerAnswer
V
T Y
S U
R
X Z
W
5050
Printing a Tree in OrderPrinting a Tree in Order
5151
Traversing a Binary TreeTraversing a Binary Tree
Inorder traversalInorder traversal Left – Root – Right Left – Root – Right
Preorder traversalPreorder traversal Root – Left – Right Root – Left – Right
Postorder traversalPostorder traversal Left – Right – Root Left – Right – Root
5252
Inserting an Entry (1)Inserting an Entry (1)
5353
Inserting an Entry (2)Inserting an Entry (2)
5454
Inserting an EntryInserting an Entry
5555
User-Defined TypesUser-Defined Types Expressing an algorithm is often more Expressing an algorithm is often more
convenient if types other than those convenient if types other than those provided as primitives in the provided as primitives in the programming languageprogramming language
Many modern programming languages Many modern programming languages allow programmers to define additional allow programmers to define additional data types, using the primitive types data types, using the primitive types and structures as building blocksand structures as building blocks
5656
Customized data typesCustomized data types User-defined data typeUser-defined data type = template for a = template for a
heterogeneous structureheterogeneous structure Abstract data typeAbstract data type = user-defined data type = user-defined data type
with methods for access and manipulationwith methods for access and manipulation ClassClass = abstract data type with extra features = abstract data type with extra features
Characteristics can be inheritedCharacteristics can be inherited Contents can be encapsulatedContents can be encapsulated Constructor methods to initialize new objectsConstructor methods to initialize new objects
5757
Customized Data TypesCustomized Data Typesstruct {struct {
char Name[8];char Name[8];int Age;int Age;float SkillRating;float SkillRating;
} Employee;} Employee;typedef struct {typedef struct {
char Name[8];char Name[8];int Age;int Age;float SkillRating;float SkillRating;
} EmployeeType;} EmployeeType;EmployeeType DistManager, SalesRep1, SalesRep2;EmployeeType DistManager, SalesRep1, SalesRep2;
5858
Declaration of Nodes of a Declaration of Nodes of a Binary TreeBinary Tree
typedef struct {typedef struct { char data;char data; Node* left;Node* left; Node* right;Node* right;} Node;} Node;
Node* root;Node* root;
5959
C++ ClassC++ Class
6060
Using ClassesUsing Classes
StackOfIntegers StackOne(50);StackOfIntegers StackOne(50); StackOne.push(106);StackOne.push(106); int OldValue = StackOne.pop();int OldValue = StackOne.pop();
6161
Standard Template LibraryStandard Template Library
A collection of predefined classes in A collection of predefined classes in C++ that describe popular data C++ that describe popular data structuresstructures
The programmer is thus relieved The programmer is thus relieved from the task of describing these from the task of describing these structures in detailstructures in detail
6262
Pointers in Machine Pointers in Machine LanguageLanguage
Machine language defined in Appendix CMachine language defined in Appendix C Load data (immediate addressing)Load data (immediate addressing)
2RXY2RXY Load address (direct addressing)Load address (direct addressing)
1RXY1RXY Load through pointer (indirect addressing)Load through pointer (indirect addressing)
DRXYDRXY DR0SDR0S
Save through pointerSave through pointer ER0SER0S
XY
R
S
6363
Expanding the Machine Expanding the Machine Language to Take Advantage Language to Take Advantage
of Pointersof Pointers
6464
Loading a Register from a Loading a Register from a Memory Cell Located by a Memory Cell Located by a
Pointer in a RegisterPointer in a Register
6565
Mini ReviewMini Review Suppose the machine language has been Suppose the machine language has been
extended to include pointer operations. extended to include pointer operations. Moreover, suppose register 8 contains the Moreover, suppose register 8 contains the pattern DB, the memory cell at address DB pattern DB, the memory cell at address DB contains the pattern CA, and the cell at contains the pattern CA, and the cell at address A5 contains the pattern CA. What address A5 contains the pattern CA. What bit pattern will be in register 5 bit pattern will be in register 5 immediately after executing the following immediately after executing the following instructions:instructions: 15A515A5 25CA25CA D508D508
6666
AnswersAnswers
CACA CACA CACA
6767
ExerciseExercise
Review problems Review problems
2, 5, 8, 14, 16, 19, 24, 26, 30, 2, 5, 8, 14, 16, 19, 24, 26, 30, 4444