Cs 261 - Data Structures Abstract Data Types (Adts)
Cs 261 - Data Structures Abstract Data Types (Adts)
2
Three Levels of Abstraction
• ADT - Abstract Data Type, language
independent
– Defines what it is.
5
The Interface View – How to Use
• Gives specific names to operations
• In C, interface is defined by .h files
6
Interface – How to Use in C
struct stack;
void initStack(struct stack *stk);
void pushStack(struct stack *stk, double val);
double topStack (struct stack *stk);
void popStack (struct stack *stk);
int isEmptyStack (struct stack *stk);
7
Interface – Behavior Constraints
In addition to names, the interface also specifies:
• Meaning of ADT
– E.g., LIFO properties of stack, etc.
• Behavior constraints
– E.g., want Push and Pop to be constant time
8
The Classic ADTs
• Bag, Ordered Bag: simple collections of data
10
Bag ADT
• Definition: Maintains an unordered
collection of data elements
• Operations:
– Initialize the bag
– Add/Remove a data element
– Check if the bag contains a given element
– Check the size of the bag
initBag (container);
addBag (container, value);
containsBag (container, value);
removeBag (container, value);
sizeBag (container);
12
Worksheet 0
13
Interface .h File for a Bag
# define TYPE double
# define MAX_SIZE 100
struct Bag {
TYPE data[MAX_SIZE];
int size;
};
/* function prototypes */
void initBag (struct Bag *b);
void addBag (struct Bag *b, TYPE val);
int containsBag (struct Bag * b, TYPE val);
void removeBag (struct Bag * b, TYPE val);
int sizeBag (struct Bag * b);
14
Implementation -- Add an Element to Bag
b->data[b->size] = val;
15
Test if Bag Contains an Element
int containsBag (struct Bag *b, TYPE val){
assert(b != NULL); /*check if b was initialized*/
int i = b->size - 1; /*index of the last element*/
17
Remove an Element from Bag
void removeBag (struct Bag * b, TYPE val) {
assert(b != NULL); /*check if b was initialized*/
int i = b->size-1; /*index of the last element*/
while (i >= 0) {/*exhaustive search*/
if (b->data[i] == val){ /*found it*/
/*swap last with current to avoid the gap*/
b->data[i] = b->data[b->size - 1];
b->size--; /*the size decreases by one*/
return;/*removes one occurrence*/
}
i--;
}
Complexity? O(n)
} 18
Next Lecture
19