【发布时间】:2010-08-24 12:30:19
【问题描述】:
我正在学习链表,想知道我为在链表末尾插入元素而制作的以下程序(基本上是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) 有没有更高效、更简单的算法在最后插入元素?你能引导我去找他们吗?
【问题讨论】:
-
谢谢你们。您的回答非常有帮助。你们给了很多我什至没有考虑过的品脱。我很难选择一个被接受的答案:) 所以我只会选择票数最多的答案。再次感谢。
-
我还想问的一件事是。你说我不需要退货声明。那么我将如何退出“if”语句?我的意思是,如果我传递一个空列表,则执行 if 语句,但如果我不返回 0,那么接下来的两个语句也将被执行。不是吗?我想我应该把最后两行放在一个 else 块中。这样就够了吗?还是我犯了一个逻辑错误?
-
将该函数的剩余部分放在 else{} 分支中,这样 if 确实可以工作。
-
你应该做一个结构来结合开始和结束。
标签: c linked-list