0% found this document useful (0 votes)
62 views

DataStructureII (ADT)

Uploaded by

syrill123
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views

DataStructureII (ADT)

Uploaded by

syrill123
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 76

12 Abstract Data Types

12.1 Foundations of Computer Science Cengage Learning

%b&ecti'es
After studying this chapter, the student shou d be ab e to(
Define the concept of an abstract data type (ADT). Define a stack, the basic operations on stacks, their app ications and ho! they can be imp emented. Define a "ueue, the basic operations on "ueues, their app ications and ho! they can be imp emented. Define a genera inear ist, the basic operations on ists, their app ications and ho! they can be imp emented. Define a genera tree and its app ication. Define a binary tree#a specia kind of tree#and its app ications. Define a binary search tree ($ST) and its app ications. Define a graph and its app ications.

12.2

12-1 BACKGROUND
Problem solving with a computer means processing data. To process data, we need to define the data type and the operation to be performed on the data. The definition of the data type and the definition of the operation to be applied to the data is part of the idea behind an abstract data type (ADT)to hide how the operation is performed on the data. In other words, the user of an !T needs only to "now that a set of operations are available for the data type, but does not need to "now how they are applied.
12.3

Simp e ADTs
$any programming languages already define some simple !Ts as integral parts of the language. %or e&ample, the ' language defines a simple !T as an integer. The type of this !T is an integer with predefined ranges. ' also defines several operations that can be applied to this data type (addition, subtraction, multiplication, division and so on). ' e&plicitly defines these operations on integers and what we e&pect as the results. programmer who writes a ' program to add two integers should "now about the integer !T and the operations that can be applied to it.

12.#

Comp e) ADTs
lthough several simple !Ts, such as integer, real, character, pointer and so on, have been implemented and are available for use in most languages, many useful comple& !Ts are not. s we will see in this chapter, we need a list !T, a stac" !T, a +ueue !T and so on. To be efficient, these !Ts should be created and stored in the library of the computer to be used.

i
The concept of abstraction means( *. +e kno! !hat a data type can do. ,. -o! it is done is hidden.
12.*

Definition
-et us now define an !T. n abstract data type is a data type pac"aged with the operations that are meaningful for the data type. .e then encapsulate the data and the operations on the data and hide them from the user.

i
Abstract data type( *. Definition of data. ,. Definition of operations. .. /ncapsu ation of data and operation.

12.,

0ode for an abstract data type


The !T model is shown in %igure 12.1. Inside the !T are two different parts of the model0 data structure and operations (public and private).

12./

Figure *,.* The mode for an ADT

1mp ementation
'omputer languages do not provide comple& !T pac"ages. To create a comple& !T, it is first implemented and "ept in a library. The main purpose of this chapter is to introduce some common user2defined !Ts and their applications. 3owever, we also give a brief discussion of each !T implementation for the interested reader. .e offer the pseudocode algorithms of the implementations as challenging e&ercises.

12.1

12-2 STACKS
stac" is a restricted linear list in which all additions and deletions are made at one end, the top. If we insert a series of data items into a stac" and then remove them, the order of the data is reversed. This reversing attribute is why stac"s are "nown as last in, first out (-I%5) data structures.

12.4

Figure *,., Three representations of stacks

%perations on stacks
There are four basic operations, stack, push, pop and empty, that we define in this chapter. The stack operation The stack operation creates an empty stac". The following shows the format.

12.16

Figure *,.. Stack operation

The push operation The push operation inserts an item at the top of the stac". The following shows the format.

12.11

Figure *,.2 3ush operation

The pop operation The pop operation deletes the item at the top of the stac". The following shows the format.

12.12

Figure *,.4 3op operation

The empty operation The empty operation chec"s the status of the stac". The following shows the format.

This operation returns true if the stac" is empty and false if the stac" is not empty.

12.13

Stack ADT
.e define a stac" as an !T as shown below0

12.1#

/)amp e *,.* %igure 12., shows a segment of an algorithm that applies the previously defined operations on a stac" 7.

12.1*

Figure *,.5 /)amp e *,.*

Stack app ications


7tac" applications can be classified into four broad categories0 reversing data, pairing data, postponing data usage and backtracking steps. .e discuss the first two in the sections that follow. 6e'ersing data items 8eversing data items re+uires that a given set of data items be reordered so that the first and last items are e&changed, with all of the positions between the first and last also being relatively e&changed. %or e&ample, the list (2, #, /, 1, ,, 1) becomes (1, ,, 1, /, #, 2).

12.1,

/)amp e *,., In 'hapter 2 (%igure 2., on page 2/) we gave a simple 9$diagram to convert an integer from decimal to any base. lthough the algorithm is very simple, if we print the digits of the converted integer as they are created, we will get the digits in reverse order. The print instruction in any computer language prints characters from left to right, but the algorithm creates the digits from right to left. .e can use the reversing characteristic of a stac" (-I%5 structure) to solve the problem. lgorithm 12.1 shows the pseudocode to convert a decimal integer to binary and print the result. .e create an empty stac" first. Then we use a while loop to create the bits, but instead of printing them, we push them into the stac". .hen all bits are created, we e&it the loop. :ow we use another loop to pop the bits from the stac" and print them. :ote that the bits are printed in the reverse order to that in which they have been created. 12.1/

/)amp e *,., ('ontinued)

12.11

/)amp e *,., ('ontinued)

12.14

3airing data items .e often need to pair some characters in an e&pression. %or e&ample, when we write a mathematical e&pression in a computer language, we often need to use parentheses to change the precedence of operators. The following two e&pressions are evaluated differently because of the parentheses in the second e&pression0

12.26

.hen we type an e&pression with a lot of parentheses, we often forget to pair the parentheses. 5ne of the duties of a compiler is to do the chec"ing for us. The compiler uses a stac" to chec" that all opening parentheses are paired with a closing parentheses.

/)amp e *,.. lgorithm 12.2 shows how we can chec" if all opening parentheses are paired with a closing parenthesis.

12.21

/)amp e *,.. ('ontinued)

A gorithm *,., 'ontinued

12.22

Stack imp ementation


t the !T level, we use the stac" and its four operations; at the implementation level, we need to choose a data structure to implement it. 7tac" !Ts can be implemented using either an array or a lin"ed list. %igure 12./ shows an e&ample of a stac" !T with five items. The figure also shows how we can implement the stac". In our array implementation, we have a record that has two fields. The first field can be used to store information about the array. The lin"ed list implementation is similar0 we have an e&tra node that has the name of the stac". This node also has two fields0 a counter and a pointer that points to the top element.
12.23

12.2#

Figure *,.7 Stack imp ementations

12-3 QUEUES
"ueue is a linear list in which data can only be inserted at one end, called the rear, and deleted from the other end, called the front. These restrictions ensure that the data is processed through the +ueue in the order in which it is received. In other words, a +ueue is a first in, first out (F1F%) structure.

12.2*

Figure *,.8 T!o representation of "ueues

%perations on "ueues
lthough we can define many operations for a +ueue, four are basic0 +ueue, en+ueue, de+ueue and empty, as defined below. The queue operation The +ueue operation creates an empty +ueue. The following shows the format.

12.2,

Figure *,.9 The "ueue operation

The enqueue operation The en+ueue operation inserts an item at the rear of the +ueue. The following shows the format.

12.2/

Figure *,.*: The en"ueue operation

The dequeue operation The de+ueue operation deletes the item at the front of the +ueue. The following shows the format.

12.21

Figure *,.** The de"ueue operation

The empty operation The empty operation chec"s the status of the +ueue. The following shows the format.

This operation returns true if the +ueue is empty and false if the +ueue is not empty.

12.24

;ueue ADT
.e define a +ueue as an !T as shown below0

12.36

/)amp e *,.2 %igure 12.12 shows a segment of an algorithm that applies the previously defined operations on a +ueue <.

12.31

Figure *,.*, /)amp e *,.2

;ueue app ications


<ueues are one of the most common of all data processing structures. They are found in virtually every operating system and networ" and in countless other areas. %or e&ample, +ueues are used in online business applications such as processing customer re+uests, =obs and orders. In a computer system, a +ueue is needed to process =obs and for system services such as print spools.

12.32

/)amp e *,.4 <ueues can be used to organi>e databases by some characteristic of the data. %or e&ample, imagine we have a list of sorted data stored in the computer belonging to two categories0 less than 1666, and greater than 1666. .e can use two +ueues to separate the categories and at the same time maintain the order of data in their own category. lgorithm 12.3 shows the pseudocode for this operation.

12.33

/)amp e *,.4 ('ontinued)

12.3#

/)amp e *,.4 ('ontinued)

A gorithm *,.. 'ontinued

12.3*

/)amp e *,.5 nother common application of a +ueue is to ad=ust and create a balance between a fast producer of data and a slow consumer of data. %or e&ample, assume that a 'P9 is connected to a printer. The speed of a printer is not comparable with the speed of a 'P9. If the 'P9 waits for the printer to print some data created by the 'P9, the 'P9 would be idle for a long time. The solution is a +ueue. The 'P9 creates as many chun"s of data as the +ueue can hold and sends them to the +ueue. The 'P9 is now free to do other =obs. The chun"s are de+ueued slowly and printed by the printer. The +ueue used for this purpose is normally referred to as a spool +ueue.

12.3,

;ueue imp ementation


t the !T level, we use the +ueue and its four operations at the implementation level. .e need to choose a data structure to implement it. +ueue !T can be implemented using either an array or a lin"ed list. %igure 12.13 on page 324 shows an e&ample of a +ueue !T with five items. The figure also shows how we can implement it. In the array implementation we have a record with three fields. The first field can be used to store information about the +ueue. The lin"ed list implementation is similar0 we have an e&tra node that has the name of the +ueue. This node also has three fields0 a count, a pointer that points to the front element and a pointer that points to the rear element.
12.3/

12.31

Figure *,.*. ;ueue imp ementation

12-4 GENERAL LINEAR LISTS


7tac"s and +ueues defined in the two previous sections are restricted inear ists. genera inear ist is a list in which operations, such as insertion and deletion, can be done anywhere in the listat the beginning, in the middle or at the end. %igure 12.1# shows a general linear list.

12.34

Figure *,.*2 <enera inear ist

%perations on genera inear ists


lthough we can define many operations on a general linear list, we discuss only si& common operations in this chapter0 list, insert, delete, retrieve, traverse and empty. The list operation The list operation creates an empty list. The following shows the format0

12.#6

The insert operation 7ince we assume that data in a general linear list is sorted, insertion must be done in such a way that the ordering of the elements is maintained. To determine where the element is to be placed, searching is needed. 3owever, searching is done at the implementation level, not at the !T level.

12.#1

Figure *,.*4 The insert operation

The delete operation !eletion from a general list (%igure 12.1,) also re+uires that the list be searched to locate the data to be deleted. fter the location of the data is found, deletion can be done. The following shows the format0

12.#2

Figure *,.*5 The de"ueue operation

The retrieve operation ?y retrieval, we mean access of a single element. -i"e insertion and deletion, the general list should be first searched, and if the data is found, it can be retrieved. The format of the retrieve operation is0

12.#3

Figure *,.*7 The retrie'e operation

The traverse operation @ach of the previous operations involves a single element in the list, randomly accessing the list. -ist traversal, on the other hand, involves se+uential access. It is an operation in which all elements in the list are processed one by one. The following shows the format0

The empty operation The empty operation chec"s the status of the list. The following shows the format0
12.##

The empty operation The empty operation chec"s the status of the list. The following shows the format0

This operation returns true if the list is empty, or false if the list is not empty.

12.#*

<enera inear ist ADT


.e define a general linear list as an !T as shown below0

12.#,

/)amp e *,.7 %igure 12.11 shows a segment of an algorithm that applies the previously defined operations on a list -. :ote that the third and fifth operation inserts the new data at the correct position, because the insert operation calls the search algorithm at the implementation level to find where the new data should be inserted. The fourth operation does not delete the item with value 3 because it is not in the list.

12.#/

Figure *,. *8 /)amp e *,.7

<enera inear ist app ications


Aeneral linear lists are used in situations in which the elements are accessed randomly or se+uentially. %or e&ample, in a college a linear list can be used to store information about students who are enrolled in each semester.

12.#1

/)amp e *,.8 ssume that a college has a general linear list that holds information about the students and that each data element is a record with three fields0 I!, :ame and Arade. lgorithm 12.# shows an algorithm that helps a professor to change the grade for a student. The delete operation removes an element from the list, but ma"es it available to the program to allow the grade to be changed. The insert operation inserts the changed element bac" into the list. The element holds the whole record for the student, and the target is the I! used to search the list.

12.#4

/)amp e *,.8 ('ontinued)

12.*6

/)amp e *,.9 'ontinuing with @&ample 12.1, assume that the tutor wants to print the record of all students at the end of the semester. lgorithm 12.* can do this =ob. .e assume that there is an algorithm called Print that prints the contents of the record. %or each node, the list traverse calls the Print algorithm and passes the data to be printed to it.

12.*1

/)amp e *,.9 ('ontinued)

12.*2

<enera inear ist imp ementation


t the !T level, we use the list and its si& operations but at the implementation level we need to choose a data structure to implement it. general list !T can be implemented using either an array or a lin"ed list. %igure 12.14 shows an e&ample of a list !T with five items. The figure also shows how we can implement it. The lin"ed list implementation is similar0 we have an e&tra node that has the name of the list. This node also has two fields, a counter and a pointer that points to the first element.

12.*3

12.*#

Figure *,.*9 <enera inear ist imp ementation

12-5 TREES
tree consists of a finite set of elements, called nodes (or 'ertices) and a finite set of directed ines, called arcs, that connect pairs of the nodes.

12.**

Figure *,.,: Tree representation

.e can divided the vertices in a tree into three categories0 the root, leaves and the internal nodes. Table 12.1 shows the number of outgoing and incoming arcs allowed for each type of node.

12.*,

@ach node in a tree may have a subtree. The subtree of each node includes one of its children and all descendents of that child. %igure 12.21 shows all subtrees for the tree in %igure 12.26.

12.*/

Figure *,.,* Subtrees

12-6 BINARY TREES


binary tree is a tree in which no node can have more than two subtrees. In other words, a node can have >ero, one or two subtrees.

12.*1

Figure *,.,, A binary tree

6ecursi'e definition of binary trees


In 'hapter 1 we introduced the recursive definition of an algorithm. .e can also define a structure or an !T recursively. The following gives the recursive definition of a binary tree. :ote that, based on this definition, a binary tree can have a root, but each subtree can also have a root.

12.*4

%igure 12.23 shows eight trees, the first of which is an empty binary tree (sometimes called a null binary tree).

12.,6

Figure *,.,. /)amp es of binary trees

%perations on binary trees


The si& most common operations defined for a binary tree are tree (creates an empty tree), insert, delete, retrieve, empty and traversal. The first five are comple& and beyond the scope of this boo". .e discuss binary tree traversal in this section.

12.,1

$inary tree tra'ersa s binary tree traversal re+uires that each node of the tree be processed once and only once in a predetermined se+uence. The two general approaches to the traversal se+uence are depth=first and breadth=first traversal.

12.,2

Figure *,.,2 Depth=first tra'ersa of a binary tree

/)amp e *,.*: %igure 12.2* shows how we visit each node in a tree using preorder traversal. The figure also shows the wal"ing order. In preorder traversal we visit a node when we pass from its left side. The nodes are visited in this order0 , ?, ', !, @, %.

12.,3

Figure *,.,4 /)amp e *,.*:

/)amp e *,.** %igure 12.2, shows how we visit each node in a tree using breadth2first traversal. The figure also shows the wal"ing order. The traversal order is , ?, @, ', !, %.

12.,#

Figure *,.,5 /)amp e *,.**

$inary tree app ications


?inary trees have many applications in computer science. In this section we mention only two of them0 3uffman coding and e&pression trees.

-uffman coding 3uffman coding is a compression techni+ue that uses binary trees to generate a variable length binary code from a string of symbols. .e discuss 3uffman coding in detail in 'hapter 1*.

12.,*

/)pression trees n arithmetic e&pression can be represented in three different formats0 infi), postfi) and prefi). In an infi& notation, the operator comes between the two operands. In postfi& notation, the operator comes after its two operands, and in prefi& notation it comes before the two operands. These formats are shown below for addition of two operands and ?.

12.,,

12.,/

Figure *,.,7 /)pression tree

12-7 BINARY SEARCH TREES


binary search tree (?7T) is a binary tree with one e&tra property0 the "ey value of each node is greater than the "ey values of all nodes in each left subtree and smaller than the value of all nodes in each right subtree. %igure 12.21 shows the idea.

12.,1

Figure *,.,8 $inary search tree ($ST)

/)amp e *,.*, %igure 12.24 shows some binary trees that are ?7Ts and some that are not. :ote that a tree is a ?7T if all its subtrees are ?7Ts and the whole tree is also a ?7T.

12.,4

Figure *,.,9 /)amp e *,.*,

very interesting property of a ?7T is that if we apply the inorder traversal of a binary tree, the elements that are visited are sorted in ascending order. %or e&ample, the three ?7Ts in %igure 12.24, when traversed in order, give the lists (3, ,, 1/), (1/, 14) and (3, ,, 1#, 1/, 14).

i
An inorder tra'ersa of a $ST creates a ist that is sorted in ascending order.

12./6

nother feature that ma"es a ?7T interesting is that we can use a version of the binary search we used in 'hapter 1 for a binary search tree. %igure 12.36 shows the 9$- for a ?7T search.

12./1

Figure *,..: 1norder tra'ersa of a binary search tree

$inary search tree ADTs


The !T for a binary search tree is similar to the one we defined for a general linear list with the same operation. s a matter of fact, we see more ?7T lists than general linear lists today. The reason is that searching a ?7T is more efficient than searching a linear list0 a general linear list uses se+uential searching, but ?7Ts use a version of binary search.

12./2

$ST imp ementation


?7Ts can be implemented using either arrays or lin"ed lists. 3owever, lin"ed list structures are more common and more efficient. The implementation uses nodes with two pointers, left and right.

12./3

Figure *,..* A $ST imp ementation

12-8 GRAPHS
graph is an !T made of a set of nodes, called 'ertices, and set of lines connecting the vertices, called edges or arcs. .hereas a tree defines a hierarchical structure in which a node can have only one single parent, each node in a graph can have one or more parents. Araphs may be either directed or undirected. In a directed graph, or digraph, each edge, which connects two vertices, has a direction from one verte& to the other. In an undirected graph, there is no direction. %igure 12.32 shows an e&ample of both a directed graph (a) and an undirected graph (b).
12./#

Figure *,.., <raphs 12./*

/)amp e *,.*. map of cities and the roads connecting the cities can be represented in a computer using an undirected graph. The cities are vertices and the undirected edges are the roads that connect them. If we want to show the distances between the cities, we can use weighted graphs, in which each edge has a weight that represents the distance between two cities connected by that edge. /)amp e *,.*2 nother application of graphs is in computer networ"s ('hapter ,). The vertices can represent the nodes or hubs, the edges can represent the route. @ach edge can have a weight that defines the cost of reaching from one hub to an ad=acent hub. router can use graph algorithms to find the shortest path between itself and the final destination of a pac"et. 12./,

You might also like