Implementing arraylist in C -
i have created program add 2 types of items in system. have created 2 structures 2 different items. have created method add items system , store each item in array. encountered problem when gonna implement delete feature, problem if have record @ array memory index 2, if delete there unused space, between memory index 1 , 3. how can overcome ? in java , there arraylist dynamically allocates space. in c know there dynamic memory allocation , how can implement work delete feature ?
here have done far :-
#include <stdio.h> #include <string.h> struct routers { int device_no; char device_name[30]; int no_of_items; int price; char description[30]; }; /**declared of struct routers store structure objects **/ struct routers routerlist[5]; struct controllers { int device_no; char device_name; int no_of_items; int price; char description[30]; }; void addnewitem(); int main() { addnewitem(); return 0; } void addnewitem(){ int item; int choice=0; int arraysize=0; do{ printf("press 1 add router \npress 2 add controller \n"); scanf("%d",&item); printf("%d",item); if(item==1){ printf("\nenter device no:\n"); scanf("%d",&routerlist[arraysize].device_no); printf("enter device name\n"); fflush(stdin); //flush buffer gets(routerlist[arraysize].device_name); printf("enter number of items\n"); scanf("%d",&routerlist[arraysize].no_of_items); printf("enter price\n"); scanf("%d",&routerlist[arraysize].price); printf("enter description\n"); fflush(stdin); gets(routerlist[arraysize].description); } arraysize++; printf("do want add item? \npress 1 add \npress 2 cancel\n"); scanf("%d",&choice); }while(choice==1); }
thank time.
depending on time complexity requirements, there 2 approaches:
use list. list data structure every item knows next item stored. implemented data structure holding pointer 2 objects of own kind (the previous 1 , next one). way, when item deleted, pointers of next , previous items can adjusted gap closed.
this means, deleting element fast, accessing element position requires searching element beginning, slow.
use array. array data structure items stored consecutively. when item deleted, gap filled shifting following elements.
this means, accessing element position fast, because arithmetic operations involved, deleting element slow, because possibly large number of elments have copied.
Comments
Post a Comment