July 21, 2009
Programming and Data Structure
1
Introduction
• A linked list is a data structure which can change during execution.
– Successive elements are connected by pointers. – Last element points to NULL. – It can grow or shrink in size during execution of a program. – It can be made just as long as required. – It does not waste memory space. A
July 21, 2009
head
B
Programming and Data Structure
C
2
• Keeping track of a linked list:
– Must know the pointer to the first element of the list (called start, head, etc.).
• Linked lists provide flexibility in allowing the items to be rearranged efficiently.
– Insert an element. – Delete an element.
July 21, 2009
Programming and Data Structure
3
Illustration: Insertion
A B C
X
Item to be inserted
A
B
C
X
July 21, 2009 Programming and Data Structure 4
Illustration: Deletion
Item to be deleted
A
B
C
A
B
C
July 21, 2009
Programming and Data Structure
5
In essence ...
• For insertion:
– A record is created holding the new item. – The next pointer of the new record is set to link it to the item which is to follow it in the list. – The next pointer of the item which is to precede it must be modified to point to the new item.
• For deletion:
– The next pointer of the item immediately preceding the one to be deleted is altered, and made to point to the item following the deleted item.
July 21, 2009 Programming and Data Structure 6
Array versus Linked Lists
• Arrays are suitable for:
– Inserting/deleting an element at the end. – Randomly accessing any element. – Searching the list for a particular value.
• Linked lists are suitable for:
– – – – Inserting an element. Deleting an element. Applications where sequential access is required. In situations where the number of elements cannot be predicted beforehand.
Programming and Data Structure 7
July 21, 2009
Types of Lists
• Depending on