Subject: Data Structures & Algorithms: in The Name of Allah The Most Beneficent The Most Merciful
Subject: Data Structures & Algorithms: in The Name of Allah The Most Beneficent The Most Merciful
Lecture : 07
a. shopping list,
b. groceries list,
c. list of people to invite to a dinner
d. List of presents to give
Lists
A list is collection of items that are all of the same
type (grocery items, integers, names)
current size
A 2 6 8 7 1
3 5
1 2 3 4 5
List Implementation
add(9); current position is 3. The new list would thus
be: (2, 6, 8, 9, 7, 1)
We will need to shift everything to the right of 8 one
place to the right to make place for the new element ‘9’.
current size
step 1: A 2 6 8 7 1
3 5
1 2 3 4 5 6
current size
Step 2: A 2 6 8 9 1
5 5
1 2 3 4 5
Implementing Lists
remove(): removes the element at the current
index
current size
Step 1: A 2 6 8 9 1
5 6
1 2 3 4 5 6
5
current size
Step 2: A 2 6 8 9 1
5 5
1 2 3 4 5
int find(int X)
{
int j;
for(j=1; j < size+1; j++ )
if( A[j] == X ) break;
find
Worst-case: may have to search the entire array
Average-case: search at most half the array.
Object/data Next/link
head
2 6 8 7 1 size=5
Linked List
Note some features of the list:
Need a head to point to the first node of the list.
Otherwise we won’t know where the start of the list
is.
Linked List
Note some features of the list:
Need a head to point to the first node of the list.
Otherwise we won’t know where the start of the
list is.
The current here is a pointer, not an index.
Linked List
Note some features of the list:
Need a head to point to the first node of the list.
Otherwise we won’t know where the start of the
list is.
The current here is a pointer, not an index.
The next field in the last node points to nothing.
We will place the memory address NULL which is
guaranteed to be inaccessible.
Linked List
Actual picture in memory:
1051 6
1052 1063
current 1053 1063
1054 2
head 1055 1051
1056
2 6 8 7 1 1057 7
1058 1060
current 1059
1060 1
1061 0
head 1062 1054
1063 8
1064 1057
1065
Linked List
Linked Lists: some Properties
This linked list has four nodes. The address of the first node is stored in the
pointer head. Each node has two components: info to store the info, and link, to
store the address of the next node.