Lecture 19: Introduction to Linked lists
Objectives of this lecture
q Learn the basic ideas about linked list and the nature
of its structure.
What is a linked list?
q Implementation of linked list is not part of the
syllabus. However, we need to have an
idea about its structure to be able to understand the lectures on searching and
sorting.
q Thus, what follows is just an introduction. You will implement its operations and learn
more about it in ICS202.
q Linked list, like stack and queue is a homogeneous
liner list consisting of nodes in which each node is liked to the next.
q However, unlike stack and queue, an item can be
deleted at any location in the list, and an item can be added (inserted) at any
location provided the order of the items in the list is maintained.
q Thus, linked list is often referred to as key-ordered structure, whereas, stack and queue are referred to
as time-ordered structures. i.e.,
in queue and stack, the position of an item depends on the time it is added but in linked list, the poison of an item depends on the item itself.
q The following figures shows the format of a linked
list and how it behaves on insertion and deletion.
q If p is inserted, the list
becomes:
q If n is deleted, the list becomes:
q The following are declarations and function prototypes
that are required for the implementation of linked list:
typedef
struct node_type{ ITEM_TYPE item;
Struct node_type *next;
} NODE_TYPE;
typedef
NODE_TYPE *NODE_PTR;
typedef
NODE_TYPE *LIST_TYPE;
typedef
enum {FALSE TRUE} BOOLEAN;
void
create_list(LIST_TYPE *list);
BOOLEAN
empty_list(LIST_TYPE *list);
BOOLEAN
full_list(LIST_TYPE *list);
void
traverse_list(LIST_TYPE *list);
insert(LIST_TYPE
*list, ITEM_TYPE new_item);
delete(LIST_TYPE
*list, ITEM_TYPE *old_item);
q Note: The
function traverse_list is used to visit each node of the list to process it
(say print it) without deleting it. Its
implementation is shown below:
void
traverse_list(LIST_TYPE *list)
{ NODE_PTR temp_ptr;
temp_ptr= *list;
while (temp_ptr != NULL)
{
process(temp_ptr->item); /*
this can be replaced by
printf */
temp_ptr=temp_ptr->next;
}
}