I am studying linked lists and want to know if the following program (basically the InsertAtEnd function) is executed correctly, which I did to insert elements at the end of the list.
The basic idea is that * HEAD points to the first element of the list and * LAST points to the last element. This saves time and computation when moving to the last item in a list, and then adds items.
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
int InsertAtEnd(struct node **, struct node **, int);
int main()
{
struct node *HEAD=NULL;
struct node *LAST=NULL;
int i=1;
for(i=1;i<11;i++)
{
InsertAtEnd(&HEAD,&LAST,i);
}
}
int InsertAtEnd(struct node **headref,struct node **lastref,int i)
{
struct node *newnode=malloc(sizeof(struct node));
newnode->data=i;
newnode->next=NULL;
if(*headref==NULL)
{
*headref=newnode;
*lastref=newnode;
return 0;
}
(*lastref)->next=newnode;
*lastref=(*lastref)->next;
return 0;
}
The questions I want to ask are:
a) Is the above code correct for adding elements at the end (for example, the InsertAtEnd function)? (Note: I tested it on my machine and it works as expected. But I still want to confirm people from you)
b) Is the code efficient (InsertAtEnd function)?
c) ( InsertAtEnd), .
d) ? ?