基本思想是*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)是否有更有效和简单的算法来插入元素到末尾?能否指导我去查看相关资料?