Professional Documents
Culture Documents
Lec 3
Lec 3
• You would like to use an array data structure but you do not know the
size of array at compile time.
• You find out when the program executes that you need an integer
array of size n=20.
Delete[] y
• We can not do this to x Array because we did not use new to create it.
Static vs. Dynamic Memory Allocation
Static Memory Allocation Dynamic Memory Allocation
• At compile time • At run time
• Amount of memory needed is known in • No need to know in advance
advance • Only required amount of memory allocated
• Finite amount of memory allocated • No memory wastage
• Memory wastage incase allocated space not
utilized fully • It will increase run time
• As memory allotted before run time, saves
run time • Slow allocation
• Fast allocation • Memory can be freed once used
• Allocated space can never be freed • Examples: Dynamic array, pointers
• Examples : Arrays, structure etc
The List Data Structure
• It is among the most generic data structures
• Real Life:
a. Shopping list
b. Groceries list
c. List of people to invite dinner
d. List of presents to get
List
• A list is collection of items that are all of the same type.
• The items, or elements of the list, are stored in some particular order.
1. Use the actual index of the element: insert after element 3, get element
number 6. This approach is taken by arrays.
2. Use a “current” marker or pointer to refer to a particular position in the list.
List Operations
• If we use the “current” marker, the following four methods would be
useful:
0 1 2 3 4
current size
3 5
List implementation
• add(9): current position is 3. The new list would now be (2,6,8,9,7,1)
• Thus we need to shift every thing to the one position right of the
current position, so that we can make space for new element 9 at
current position.
2 6 8 7 1
0 1 2 3 4 5
current size
3 6
List implementation
• next():
2 6 8 9 7 1
0 1 2 3 4 5
current size
4 6
List implementation
• There are special cases for positioning the current pointer:
2 6 8 9 1 current size
0 1 2 3 4 5 4 6
2 6 8 9 1
current size
4 5
0 1 2 3 4
List implementation
• find(x): traverse the array until x is located
int find(int x)
{
Int j;
for(j=1;j<size;j++)
{
if(A[j]==x)
break;
}
if(j<size)
{
current=j;
return 1;
}
return 0;
}
List implementation
• get() return A[current]
• update(x) A[current]=x
• length() return size
• back() curren--
• start() current=1
• end() current=size
Analysis of Array Lists
• add
We have to move every element to the right of current to make space for the
new element.