Вы находитесь на странице: 1из 12

www.

aptio
ww.aptionline.com

Link List

One disadvantage
age of uusing arrays to store data is that
at arrays are static
structures and therefore
fore can
cannot be easily extended or reducedced to fit
f the data
set. Arrays are also expensiv
expensive to maintain new insertions and deletions.
dele In
this chapter we consider
sider ano
another data structure called Linkeded Lists that
addresses some of thehe limita
limitations of arrays.

Definition:

In computer science
science, a linked list is a data structure consisting
consisti of a
group of nodes which h togeth
together represent a sequence. Under er the simplest
si
form, each node is composed of a data and a reference (in other words, w
a link) to the next nodee in th
the sequence; more complex variants
riants add
a
additional links. This
s structur
structure allows for efficient insertion or removal
remo of
elements from any position
osition iin the sequence.

Linked lists are amongng the ssimplest and most common data ta structures.
struct They
can be used to implement
ment se
several other common abstract data types,
typ
including lists (the abstract
bstract ddata type), stacks, queues, associative
ssociative arrays,
and S-expressions, though
hough it is not uncommon to implement nt the other
o data
structures directly without
ithout usi
using a list as the basis of implementat
ementation.
Array versus Linked
ed Lists

Arrays are suitable for:

Inserting/deleting an elem
element at the end.

Randomly accessing
g any e
element.

Searching the list for a par


particular value.

Linked lists are suitable


table for
for:

Inserting an element.

Deleting an element.

Applications where sequen


sequential access is required.

Data Structure: Linked list


www.aptio
ww.aptionline.com

In situations where the nu


number of elements cannot be predicted
redicted
beforehand.

Basic Operations on a List

Creating a list

Traversing the list

Inserting an item in
n the list

Deleting an item from


om the list

Concatenating two lists int


into one

Types of Link List

Singly linked list

Singly linked lists contain


ntain no
nodes which have a data field as well as a next
field, which points to the nex
next node in the linked list.

A singly linked list whose


hose no
nodes contain two fields: an integer
ger value
valu and a
link to the next node

Linked list is one of the


he fund
fundamental data structures in C. Linked listl is a
dynamic data structure re whose length can be increased or decreased
decrease at run
time. How Linked liststs are di
different from arrays? Consider the following
follo
points:
An array is a static
ic data structure. This means the length th of array
arr cannot
be altered at run time. W While, a linked list is a dynamic
c data structure.
str
In an array, all thee eleme
elements are kept at consecutive memory
emory locations
lo
while in a linked list
ist the e
elements (or nodes) may be kept at any location
but still connectedd to each other.
struct test_struct
{
int val;
struct test_struct *next;
};

Data Structure: Linked list


www.aptionline.com

How a node is created?


A node is created by allocating memory to a structure (as shown in above
point) in the following way :
struct test_struct *ptr = (struct test_struct*)malloc(sizeof(struct
test_struct));
So, as we can see above, the pointer ptr now contains address of a newly
created node. If the linked list is empty and first node is created then it is
also known as head node.
Once a node is created, then it can be assigned the value (that it is created
to hold) and its next pointer is assigned the address of next node. If no next
node exists (or if its the last node) then as already discussed, a NULL is
assigned. This can be done in following way :
ptr->val = val;
ptr->next = NULL;
..

while(ptr != NULL)
{
if(ptr->val == val)
{
found = true;
break;
}
else
{
ptr = ptr->next;
}
}

How a node is deleted?


A node is deleted by first finding it in the linked list and then calling free ()
on the pointer containing its address. If the deleted node is any node other
than the first and last node then the next pointer of the node previous to
the deleted node needs to be pointed to the address of the node that is just
after the deleted node. Its just like if a person breaks away from a human
chain then the two persons (between whom the person was) needs to join
hand together to maintain the chain.
A Practical C Linked List Example

Data Structure: Linked list


www.aptionline.com

Here is a practical example that creates a linked list, adds some nodes to it,
searches and deletes nodes from it.
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>

struct test_struct
{
int val;
struct test_struct *next;
};
struct test_struct *head = NULL;
struct test_struct *curr = NULL;
struct test_struct* create_list(int val)
{
printf("\n creating list with headnode as [%d]\n",val);
struct test_struct *ptr = (struct test_struct*)malloc(sizeof(struct
test_struct));
if(NULL == ptr)
{
printf("\n Node creation failed \n");
return NULL;
}
ptr->val = val;
ptr->next = NULL;

head = curr = ptr;


return ptr;
}

struct test_struct* add_to_list(int val, bool add_to_end)


{
if(NULL == head)
{
return (create_list(val));
}

if(add_to_end)
printf("\n Adding node to end of list with value [%d]\n",val);
else
printf("\n Adding node to beginning of list with value [%d]\n",val);

Data Structure: Linked list


www.aptionline.com

struct test_struct *ptr = (struct test_struct*)malloc(sizeof(struct


test_struct));
if(NULL == ptr)
{
printf("\n Node creation failed \n");
return NULL;
}
ptr->val = val;
ptr->next = NULL;

if(add_to_end)
{
curr->next = ptr;
curr = ptr;
}
else
{
ptr->next = head;
head = ptr;
}
return ptr;
}

struct test_struct* search_in_list(int val, struct test_struct **prev)


{
struct test_struct *ptr = head;
struct test_struct *tmp = NULL;
bool found = false;
printf("\n Searching the list for value [%d] \n",val);
while(ptr != NULL)
{
if(ptr->val == val)
{
found = true;
break;
}
else
{
tmp = ptr;
ptr = ptr->next;
}
}

Data Structure: Linked list


www.aptionline.com

if(true == found)
{
if(prev)
*prev = tmp;
return ptr;
}
else
{
return NULL;
}
}

int delete_from_list(int val)


{
struct test_struct *prev = NULL;
struct test_struct *del = NULL;
printf("\n Deleting value [%d] from list\n",val);
del = search_in_list(val,&prev);
if(del == NULL)
{
return -1;
}
else
{
if(prev != NULL)
prev->next = del->next;
if(del == curr)
{
curr = prev;
}
else if(del == head)
{
head = del->next;
}
}

free(del);
del = NULL;
return 0;
}

Data Structure: Linked list


www.aptionline.com

void print_list(void)
{
struct test_struct *ptr = head;
printf("\n -------Printing list Start------- \n");
while(ptr != NULL)
{
printf("\n [%d] \n",ptr->val);
ptr = ptr->next;
}
printf("\n -------Printing list End------- \n");
return;
}

int main(void)
{
int i = 0, ret = 0;
struct test_struct *ptr = NULL;
print_list();
for(i = 5; i<10; i++)
add_to_list(i,true);
print_list();
for(i = 4; i>0; i--)
add_to_list(i,false);
print_list();
for(i = 1; i<10; i += 4)
{
ptr = search_in_list(i, NULL);
if(NULL == ptr)
{
printf("\n Search [val = %d] failed, no such element found\n",i);
}
else
{
printf("\n Search passed [val = %d]\n",ptr->val);
}

print_list();

ret = delete_from_list(i);
if(ret != 0)
{
printf("\n delete [val = %d] failed, no such element found\n",i);

Data Structure: Linked list


www.aptionline.com

}
else
{
printf("\n delete [val = %d] passed \n",i);
}

print_list();
}
return 0;
}
In the code above:
The first node is always made accessible through a global head pointer.
This pointer is adjusted when first node is deleted.
Similarly there is a curr pointer that contains the last node in the list.
This is also adjusted when last node is deleted.
Whenever a node is added to linked list, it is always checked if the linked
list is empty then add it as the first node.

Doubly linked list: In a doubly linked list, each node contains, besides the
next-node link, a second link field pointing to the previous node in the
equence. The two links may be called forward(s) and backwards,
or next and prev(ious). Doubly-linked list is a more sophisticated form of
linked list data structure. Each node of the list contain two references (or
links) one to the previous node and her
to the next node.
The previous link of the first node and the next link of the last node points
to NULL. In comparison to singly-linked list, doubly-linked list requires
handling of more pointers but less information is required as one can use the
Double Linked List - C Program source code.
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
struct Node *prev;
}node;
void insert(node *pointer, int data)

Data Structure: Linked list


www.aptionline.com

{
/* Iterate through the list till we encounter the last node.*/
while(pointer->next!=NULL)
{
pointer = pointer -> next;
}
/* Allocate memory for the new node and put data in it.*/
pointer->next = (node *)malloc(sizeof(node));
(pointer->next)->prev = pointer;
pointer = pointer->next;
pointer->data = data;
pointer->next = NULL;
}
int find(node *pointer, int key)
{
pointer = pointer -> next; //First node is dummy node.
/* Iterate through the entire linked list and search for the key. */
while(pointer!=NULL)
{
if(pointer->data == key) //key is found.
{
return 1;
}
pointer = pointer -> next;//Search in the next node.
}
/*Key is not found */
return 0;
}
void delete(node *pointer, int data)
{
/* Go to the node for which the node next to it has to be deleted */
while(pointer->next!=NULL && (pointer->next)->data != data)
{
pointer = pointer -> next;
}

Data Structure: Linked list


www.aptionline.com

if(pointer->next==NULL)
{
printf("Element %d is not present in the list\n",data);
return;
}
/* Now pointer points to a node and the node next to it has to be
removed */
node *temp;
temp = pointer -> next;
/*temp points to the node which has to be removed*/
pointer->next = temp->next;
temp->prev = pointer;
/*We removed the node which is next to the pointer (which is also
temp) */
free(temp);
/* Beacuse we deleted the node, we no longer require the memory
used for it .
free() will deallocate the memory.
*/
return;
}
void print(node *pointer)
{
if(pointer==NULL)
{
return;
}
printf("%d ",pointer->data);
print(pointer->next);
}
int main()
{
/* start always points to the first node of the linked list.
temp is used to point to the last node of the linked list.*/
node *start,*temp;

Data Structure: Linked list


www.aptionline.com

start = (node *)malloc(sizeof(node));


temp = start;
temp -> next = NULL;
temp -> prev = NULL;
/* Here in this code, we take the first node as a dummy node.
The first node does not contain data, but it used because to avoid
handling special cases in insert and delete functions. */

printf("1. Insert\n");
printf("2. Delete\n");
printf("3. Print\n");
printf("4. Find\n");
while(1)
{
int query;
scanf("%d",&query);
if(query==1)
{
int data;
scanf("%d",&data);
insert(start,data);
}
else if(query==2)
{
int data;
scanf("%d",&data);
delete(start,data);
}
else if(query==3)
{
printf("The list is ");
print(start->next);
printf("\n");
}
else if(query==4)

Data Structure: Linked list


www.aptio
ww.aptionline.com

{
int data;
scanf("%d",
f("%d",&data);
int status = find(start,data);
if(status)
printf("Ele
intf("Element Found\n");
else
printf("Ele
intf("Element Not Found\n");
} } } }

Circular list :
In the last node of a list, the link field often contains a null reference,
referen a
special value used to indicate the lack of further nodes. A less commoncom
convention is to make e it poin
point to the first node of the list; in that case
ca the
list is said to be circular or circularly linked; otherwise it iss said to
be open or linear.

A circular linked list

In the case of a circular


lar doub
doubly linked list, the only change that occurs
occ is that
the end, or "tail", of the said list is linked back to the front,, or "head",
"he of the
list and vice versa.

Data Structure: Linked list

Вам также может понравиться