Я изучаю связанные списки и хочу знать, правильна ли следующая программа (в основном функция InsertAtEnd), которую я сделал для вставки элементов в конец списка.
Основная идея заключается в том, что* HEAD указывает на первый элемент списка, а * LAST указывает на последний элемент.Это экономит время и вычисления при переходе к последнему элементу списка и последующем добавлении элементов.
#include<stdio.h>
#include<stdlib.h>
// Structure for the list element/node
struct node
{
int data; // Stores the data
struct node *next; // Points to the next element in the list.
};
int InsertAtEnd(struct node **, struct node **, int); /*Declaration of the function which
inserts elements at the end.*/
int main()
{
struct node *HEAD=NULL; //Points to the first element in the list.
struct node *LAST=NULL; //Points to the last element in the list.
int i=1;
for(i=1;i<11;i++)
{
InsertAtEnd(&HEAD,&LAST,i);
}
}
// Function to insert element at the end.
int InsertAtEnd(struct node **headref,struct node **lastref,int i)
{
struct node *newnode=malloc(sizeof(struct node)); /*Allocates memory for the newnode
and store the address in pointer
newnode*/
newnode->data=i; // Assign value to the data variable of the newnode.
newnode->next=NULL; // Assign NULL to the next pointer of the newnode.
if(*headref==NULL) //Checks if the list is empty.
{
*headref=newnode; // Places the address of the new node in HEAD pointer.
*lastref=newnode; // Places the address of the new node in LAST pointer.
return 0; //Exit function
}
/* If the list is not empty, then make the next pointer of the present last node point to the new node*/
(*lastref)->next=newnode;
*lastref=(*lastref)->next; // Increment LAST to point to the new last node.
return 0;
}
Вопросы, которые я хочу специально задать:
a) Вышекод для добавления элементов в конце (т.е. функция InsertAtEnd) правильно?(Примечание: я проверил его на своей машине, и он работает, как и ожидалось. Но я все еще хочу подтвердить от вас, люди)
b) Эффективен ли код (функция InsertAtEnd)?
c)Повлияет ли эффективность кода (функция InsertAtEnd), если я попытаюсь составить более длинный список.
d) Существуют ли более эффективные и простые алгоритмы для вставки элементов в конце?Вы можете направить меня к ним?