加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 链接列表:使用最后一个指针在末尾插入

发布时间:2020-12-16 10:17:30 所属栏目:百科 来源:网络整理
导读:我正在学习链表,并想知道我在列表末尾插入元素所做的以下程序(基本上是InsertAtEnd函数)是否正确. 基本思想是* HEAD指向列表的第一个元素,* LAST指向最后一个元素.这样可以节省遍历列表最后一个元素然后添加元素的时间和计算. #includestdio.h#includestdlib
我正在学习链表,并想知道我在列表末尾插入元素所做的以下程序(基本上是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)是否有更有效和简单的算法来插入元素?你能指导我吗?

解决方法

a)似乎是正确的

b)确实如此.您可以使函数返回void,因为您不需要该int返回值

c)否.换句话说,执行时间是不变的.

d)malloc需要时间.您可以使用缓冲技术,预先对一大块节点进行malloc,然后从缓冲区中获取下一个节点.当缓冲区变为empy时,分配另一个块.可以使用统计算法来配置或甚至(复杂)计算块尺寸.

此外,您不检查malloc的NULL返回,但它可能会失败.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读