Monday, August 19, 2013

Header file for LIST IMPLEMENTATION in C using arrays in linked list

/***************** LIST IMPLEMENTATION **************/



#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int *list; 
int len;
int cap;                            //capacity
int current_position;
}list;
void initialize_list(list *l)
{
int i;
l->len=0;
l->cap=99;
l->current_position = 0;
l->list = (int *)malloc(sizeof(int) * (l->cap+1));
for(i = 0; i <= l->cap+1; i++)
{
l->list[i] = 0;

}
void print_list(list *l)
{

int k; 
for(k=0; k < l->len; k++)
printf("%d ", l->list[k]);
}
void insert_at_position(list *l, int pos, int item)
{//this function should insert the item at a given position in the list
int i, temp;
if(l->len+1 > l->cap)
{
printf("cap is full!");
}
else
{
l -> len++;
for(i = (l -> len); i >= pos; i--)
{
l -> list[i] = l -> list[i-1];
}
l->list[pos-1] = item;
}
l -> current_position = pos-1;
}
void append_l(list *l, int item)
{
int i = l -> len;
// This function will be inserting the item at the end of the list
if(l -> len+1 < l -> cap)
{
l -> list[i] = item;
(l -> len)++;
}
l -> current_position = l -> len;
}
int remove_l(list *l, int at_position)
{
// This function will remove an element from the specified position
// and return the removed value to the calling function
int i;
for(i = at_position-1; i <= l -> len; i++)
{
l -> list[i] = l -> list[i+1];
}
//l->list[pos-1] = item;
l -> len--;
l -> current_position = at_position-1;
}
void move_to_start(list *l)
{
//This function will be setting the current_position to the start of the 
//list
l -> current_position = 0; 

}
void move_to_end(list *l)
{
//This function will be setting the current_postion to last element
//of the list
l -> current_position = l -> len - 1; 
}
int current_position(list *l)
{
//This function will return the value stored in current position
//int i = l -> current_position - 1;
return l -> list[l -> current_position];

}
void move_to_position(list *l, int pos)
{
//This function will change the value of current_postition to pos
l -> current_position = pos-1;
}
void prev(list *l)
{
//This function will decrement current_postion by one, none if at start
if(l -> current_position > 1)
l -> current_position--;
}
void next(list *l)
{
//This function will increment current_position by one, none if 
//at the end
if(l -> current_position < l -> len)
l -> current_position++;
}
int find_value_at_position(list *l, int pos)
{
//This function finds the value at a given position pos in the list
return l -> list[pos-1];
}
int find_position_of_a_value(list *l, int value)
{
//This function will return the position if the value is present
//or else a negative number
int i;
for(i = 0; i < l -> len; i++)
{
if(l -> list[i] == value)
return i+1;
}
}
int size(list *l)
{
//Returns the current size of the list
return l -> len;
}

No comments: