Design a data structure that does all these operations optimally
1. Insert
2. Delete
3. Search
COnsider the intput as a set of integers. The data structure that could be used is :
struct node
{
int data;
struct node * next;
}
Now we can have an array of the pointers to nodes
struct node * array[10]; // Mapped from 0 to 9
void Insert (int x)
{
y = hash(x); // hash will reurn the number between 0 to 9
struct node * temp;
temp = createnode(x);
temp-> next = array[y]->next;
array[y]->next = temp;
}
The complexity of the insert operation is o(1)
void delete(int x)
{
y = hash(x);
struct node * temp;
temp = array[y]->next;
prev = array[y];
while(temp!= NULL)
{
if(temp->data == x)
{
prev-next = temp->next;
}
prev = temp;
temp = temp->next;
}
The complexity of the delete operation would be, worst case is when the element is at the end of the list pointed by any array index. So the worst case would be o(length of the link list)
void search(int x)
{
y = hash(x);
loop to get the value of the node.
}
The complexity will be same as the delete.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment