424,688 Members | 1,897 Online
Need help? Post your question and get tips & solutions from a community of 424,688 IT Pros & Developers. It's quick & easy.

# insert an elem into a link list

 P: n/a i wrote a function to insert an elem into a list, but it was wrong,wrong,wrong! and i have no idea about why it was wrong. If anyone know, leave your advice, thank you. #include #include typedef struct lnode { int elem; struct lnode *next; //int length; }listnode,*linklist; int initial(linklist list); int insert(linklist list,int i,int x); int main() { int i,t; linklist testlist; testlist=NULL; //p=&testlist; t=initial(testlist); printf("%d\n",t); //for(i=0;i<100;i++) // insert(testlist,i,i); //t=get(testlist,1); i=insert(testlist,1,1); printf("%d\n%d",t,i); return 1; } int initial(linklist list) { list=malloc(sizeof*list); list->next=NULL; list->elem=0; //list->length=1; return 1; } int insert(linklist list,int i,int x) { int j=0; listnode *new_node=0; listnode *plist; plist=list; if(i=1) { new_node=malloc(sizeof*new_node); new_node->elem=x; list->next=new_node; return 3; } /* for(j=0;jnext; */ while(plist&&jnext; j++; } if(!plist||j>i-1) return 0; new_node=malloc(sizeof*new_node); new_node->next=plist->next; new_node->elem=x; plist->next=new_node; return 1; } Apr 4 '06 #1
4 Replies