is this logic correct, where does counting starts in a link list, is it from 0 or 1.
b'cos when i am ading item 60 at loc 4, den the output is :
item number 1 contains 30
item number 2 contains 20
item number 3 contains 10
item number 4 contains 40
item number 5 contains 60
item number 6 contains 50

struct linklist{
int item;
struct linklist *link;
};
struct linklist *start;
int main()
{
start=NULL;//Assume the list is empty;
/*function to add elements at desired location*/
 add_at_loc(60,4);
 printf("\nElements in the list after insertion are:\n");
add_at_loc(int data,int loc)
 {
 struct linklist *new=(struct linklist*)malloc(sizeof(struct linklist));//allocate memory for node
 struct linklist *next_node, *ptr=start;//declare a pointer variable for next node, and assign start pointer to a pointer variable ptr
 int i=1;//counter
 new->item=data;//set item to data
 new->link=NULL;//set link to NULL
 if(start==NULL)//checks if list is empty
 start=new;//if list is empty , insert the node as 1st node in list
 else
 {
 while((ptr->link!=NULL)&&(i!=loc))//condition checks for last node and location match
 {
 i++;//increment to next node
 ptr=ptr->link;//assign the link of next node to point to ptr(start pointer variable)
 }
 if(i==loc)//if location is found
 {
 next_node=ptr->link;//
 ptr->link=new;
 new->link=next_node;
 }
 else
 ptr->link=new;
 }
 }
}

where does counting starts in a link list, is it from 0 or 1.

depends on whats the first input of item but I believe you used 1
actually this is the issue here:

if(i==loc)//if location is found
 {
 next_node=ptr->link;//
 ptr->link=new;
 new->link=next_node;
 }

once the node with the same value is found
here you insert the the new node to be the next node of the current
for example once node 4 is found the new node's value is inserted and becomes the next node which is node 5

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.