Sunday, May 9, 2010

Linked List Example

Recently I was recalling my linked list concepts, and I found that I know the concepts, but when programming I am missing something. So I thought I should do it once again, so I made a simple program, which can add / delete elements from linked list. here it is for your reference.

shetty.h, this file contains the basic type definitions required.
#ifndef __SHETTY_H_
#define __SHETTY_H_

typedef struct le {
int ld;
le *next;
} le;

typedef struct lh {
le *next;
} lh;

#endif // __SHETTY_H_

Shetty.cpp, this file contains all the functionality required to add or delete from the linked list. The comments are self explanatory.

#include "shetty.h"
#include "malloc.h"
#include "stdio.h"

lh list;

/********************************************
** This function adds an element to Linked
** list, the head to list and element to be
** added is given as params.
** lst - pointer to the head of the list
** ld - an integer data, u can change this
** to whatever type you want to.
********************************************/
void add_list(lh *lst, int ld)
{
le *element;
le **tmp;
element = (le *) malloc (sizeof(*element));
element->ld = ld;
element->next = NULL;

tmp = &(lst->next);
while(*tmp!=NULL)
tmp = &((*tmp)->next);
*tmp = element;
}

/********************************************
** This function removes an element from the
** Linked list
********************************************/
void remove_list(lh *lst, int ld)
{
le **tmp, **prev;
le *deleted;

tmp = &(lst->next);
prev = tmp;
while(*tmp!=NULL)
{
if((*tmp)->ld == ld)
{
deleted = (*prev)->next;
(*prev)->next = (*tmp)->next;
free(deleted);
}
prev = tmp;
tmp = &((*tmp)->next);
}
}

/**************************************
** Display the list to see elements
**************************************/
void disp_list(lh *lst)
{
le **tmp;
tmp = &(lst->next);
while(*tmp!=NULL)
{
printf("%d\t", (*tmp)->ld);
tmp = &((*tmp)->next);
}
printf("\n");
}
int main(void)
{
list.next = NULL;
add_list(&list, 25);
add_list(&list, 30);
disp_list(&list);
add_list(&list, 45);
disp_list(&list);
add_list(&list, 55);
disp_list(&list);
}

Here, only one thing is important in dealing with linked list. i.e we need to get the address of the next pointer in a temp variable, and then change this variable with different address as we traverse the list. We should not modify any of the pointers in the list while traversing, unless we want to add or delete from the list.

No comments:

Post a Comment