【发布时间】:2011-01-08 11:45:59
【问题描述】:
几天前我发布了一个关于 C 中的链接列表的问题。我认为一切正常,然后教授给我们发电子邮件说,而不是这个签名:
int insert_intlist( INTLIST* lst, int n); /* Inserts an int (n) into an intlist from the beginning*/
他无意中的意思:
int insert_intlist( INTLIST** lst, int n); /* Inserts an int (n) into an intlist from the beginning*/
我想我现在很酷,因为我有一个指向指针的指针,我可以将指针移到 main 之外,当我返回 main 时,我仍然拥有完整的链表。
他开始给我们这个:
INTLIST* init_intlist( int n )
{
INTLIST *lst; //pointer to store node
lst = (INTLIST *)malloc(sizeof(INTLIST)); //create enough memory for the node
lst->datum = n; //set the value
lst->next = NULL; //set the pointer
return lst; //return the new list
}
这只是在 main 中像这样初始化列表:
if (lst==NULL)
lst = init_intlist(i);
else
insert_intlist(lst, i);
lst 是 INTLIST* 类型,因此它定义为 INTLIST* lst。所以我从像 1 3 4 9 这样的文本文件中读取了一些数字。 它应该由此创建一个链表......所以第一个数字将转到 init_intlist(1);这是上面定义的。然后它在这种情况下抓取下一个数字 3 并调用 insert_intlist(lst, 3)。好吧,这是我的 insert_intlist,我要做的就是在列表的开头插入:
int insert_intlist(INTLIST** lst, int n )
{
INTLIST* lstTemp; //pointer to store temporary node to be added to linked list
lstTemp = (INTLIST *)malloc(sizeof(INTLIST)); //create enough memory for the node
lstTemp->datum = n; //assign the value
//check if there is anything in the list,
//there should be, but just in case
if(*lst == NULL)
{
*lst=lstTemp;
lstTemp->next=NULL;
}
else
{
lstTemp->next = *lst; //attach new node to the front
*lst = lstTemp; //incoming new node becomes the head of the list
}
return 0;
}
因此,如果列表最初包含 1,则此函数将简单地创建一个新节点,然后使此临时节点->next 指向列表的头部(我认为是 lst),然后将列表的头部重新分配给这个新的临时节点。
看起来一切正常,但是当我尝试将列表打印到屏幕上时,它只打印数字 1。
有人知道我做错了什么吗?
【问题讨论】:
-
不是很有帮助,但你有没有考虑过勒死你的教授? :)
-
我认为你应该给你的教授一个不及格的分数!
-
我同意他刚刚向全班同学发送了电子邮件,让他们知道他的 .h 文件对于各种功能都不正确……天哪,这真是一团糟。看起来教授甚至没有编码这个。也许他是从那个疯狂的教授那里得到这个任务的
标签: c linked-list