//list as an array - provide insert(), delete() and locate() functionality
#include <stdio.h>
void list_delete( int* array, int& size, int elemToDelete );
int locate( int* array, int size, int elemToLocate);
void insert( int* array, int& size, int elemToInsert );
void PrintArray( int* array, int size);
void main()
{
int array[100];
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;
array[5] = 6;
array[6] = 7;
int size = 7; //current size of the array.
//lets use the functions.
int pos = -1;
pos = locate( array, size, 0 );
if( pos == -1 )
printf("element 0 not found." );
else
printf("element 0 found at position [%d].\n", pos );
pos = locate(array, size, 6);
if( pos == -1 )
printf("element 6 not found." );
else
printf("element 6 found at position [%d].\n", pos );
PrintArray(array, size);
//insert
insert( array, size, 0);
insert( array, size, 10 );
insert( array, size, 11 );
PrintArray( array, size);
//delete
list_delete( array, size, 0 );
list_delete( array, size, 1 );
list_delete( array, size, 2 );
PrintArray( array, size );
}
int locate( int* array, int size, int elemToLocate)
{
for( int i = 0; i < size; i++ )
{
if( array[i] == elemToLocate )
return i;
}
return -1;
}
void insert( int* array, int& size, int elemToInsert )
{
//find position of where to insert the elem
int i;
for( i=0; i< size; i++ )
{
if( array[i] > elemToInsert )
break;
}
if( i != size )
{
//we need to move the array in right direction
for( int j = size; j > i; j-- )
{
array[j] = array[j-1];
}
}
array[i] = elemToInsert;
size++;
}
void list_delete( int* array, int& size, int elemToDelete )
{
//find pos of element to delete.
int i;
for( i = 0; i < size; i++ )
{
if( array[i] == elemToDelete )
break;
}
if( i == size-1 )
{
//last elem needs to be deleted
size--;
}
else if( i == size )
{
//element not found
}
else
{
/* need to move the elements to the left. */
for( int j = i; j < size-1; j++ )
array[j] = array[j+1];
size--;
}
}
void PrintArray( int* array, int size)
{
printf("\n Array is --> \n" );
printf("\n");
for( int i = 0; i < size; i++ )
{
printf("[%d]\n", array[i] );
}
printf("\n");
printf("End of array.\n");
}
Solutions to problems in the classic data structures book - "Data Structures and Algorithms by Aho, HopCroft and Ullman."
Sunday, February 21, 2010
Chapter 2: Basic Abstract Data Types. Problem 2.2.a
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment