Arrays and Linked Lists
Arrays and Linked Lists
Arrays and Linked Lists
Lists
• One Dimensional
• Multi Dimensional
Algorithms
• Traversing an array
• Visiting every elements of the array one by one in an ordered fashion.
• Algorithm
• Start
• Declare a pointer to the array base address
• Visit position
• Increment pointer
• Repeat steps 3 and 4 until the array has been fully traversed
• Exit
Algorithms
• Insertion
• Need to insert an element on a given position. The value along with its
position will be given as the user input.
• There are two cases associated with insertion to an array
• After the last element
• Before or on the position of the last element
• After the last element
• The insertion becomes trivial. If the user inputs a position at the first free element, given
that the input is within the capacity of the array, we just set the value of the array to the
user input at the position desired. The size of the array also increases by one.
• However, if the user tries to input a position greater than the bounds of the array or in a
position that creates a “bubble” in the array, the insertion operation fails.
Insertion
Insertion
• Before or at the position of the last element
• Requires a backwards traversal till the array position. At every position, you
copy over the values one place over to the right and continue the loop until
you’ve reached the position that the user has given as an input.
• This obviously requires checking whether the size hasn’t exceeded the
capacity of the array. The size of the array is also incremented given that the
insertion operation was successful.
Deletion
• There are also two cases related with deletion from an array.
• Deleting the last element
• Deleting an element before or on the position of the last element.
list. It is vital to keep track of this pointer and use it properly since a
wrong action could lead to the user losing the entire linked list!
Linked Lists
• We can also build this data structure by keeping extra information
such as the tail pointers, the middle pointer, but these depend on the
developer or the user requirements.
• We have different flavours of linked lists too. These have higher
storage requirements but present better solutions to the problem of
insertion, deletion and traversal of the linked lists
• Singly Linked Lists
• Doubly Linked Lists
• Circular Linked Lists
• Now, we shall focus on Singly Linked Lists
Singly Linked List
Algorithms
• Traversal
• Traversal is simple with linked lists. We start with a reference to the head
pointer and we visit each and every node. After visiting a node, we take the
pointer to the next node and we do so until we’ve visited all the nodes.
Insertion
• Insertion. We expect the user gives us the value he/she wants to enter
along with its position.
• Insertion at the head
• Insertion at the end
• Insertion in the middle