CS525W: Webware

Download Report

Transcript CS525W: Webware

CS2303: Systems
Programming Concepts
Class 15
Data Structures:
Implementing Stacks
Lists
Trees
Copyright 2005-2008, Michael J. Ciaraldi
1
Implementing a Stack
2
Implementing a Stack
Data we need to keep track of:
Location of stack space.
Size of stack space (number of elements).
Current top of stack and/or number used.
3
Implementing a Stack
Operations:
Create
Push
Pop
Peek
Test for empty and/or full
Delete
4
Implementing a Stack
Decisions for this example
Grow up, not down.
Top pointer points to next available cell.
Easier to handle empty stack.
Stack holds pointers (void *).
If full, do not modify stack.
5
Stack Structure
Stack is a struct.
Use typedef.
Contents:
stack_space = Pointer to base of allocated stack
space. (void **).
max_cells = Total number of cells allocated (int).
cells_used (int).
next = pointer to next free cell.
6
Operations
Stack* create_stack(int max_cells);
Allocates space for a Stack structure and the
stack itself, and initializes the structure.
Returns pointer to the Stack structure.
Returns null if error.
void delete_stack(Stack *which_stack);
Frees the stack space and the structure.
But not the things which the stack entries
point to (why not?).
7
Operations
int push(Stack *which_stack, void *ptr);
Pushes pointer ptr onto stack.
Returns 0 if successful.
Returns -1 if not.
void* pop(Stack *which_stack);
Pops top of stack, and returns it.
Returns null if empty.
What if a null was pushed earlier?
8
Linked Lists
9
Linked Lists
Characteristics:
A series of nodes (members) linked together.
Potentially unlimited size.
Could be used to implement other data
structures, e.g. stacks, queues.
10
Linked Lists
Head pointer
11
Linked Lists
Decisions:
What are the nodes?
Are the links part of the nodes?
Can nodes be added/deleted…
At the head?
At the tail?
In the middle?
How to decide position?
12
Linked Lists
Decisions:
Singly- or doubly-linked?
Affects direction of navigation.
How is the list represented?
Pointer to a structure.
Pointer to the head.
How to indicate end of list?
Null pointer?
Special node.
13
Remember
Every function must leave the list in a
consistent state.
Don’t plan on fixing up later.
Make use of iteration and/or recursion as
appropriate.
14
Trees
15
Trees
Used to show organization of data.
Hierarchy
Order
Each node has:
One parent
Zero or more children.
16
Trees
17
Trees
Decisions:
Mostly the same as lists, plus:
Maximum children for each node.
• 2 = Binary tree.
Does order of children have to be preserved?
Does tree have to be balanced?
18
Next Time
More on trees.
Allocation/deallocation: caller vs. callee.
19