如何插入在链表的开始的节点? [英] How do I insert a node at the beginning of a linked list?
本文介绍了如何插入在链表的开始的节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是错的 addAtBegin
?该列表似乎是将新创建节点
到启动后正确
,但是当控制返回到主
,新值不会被保存。
typedef结构节点
{
int数据;
结构节点*链接;
}节点;节点* createList(int数据)
{
节点* tempNode =(节点*)malloc的(的sizeof(节点));
tempNode->数据=数据;
tempNode->链接= NULL;
返回tempNode;
}无效addAtBegin(节点*启动,int数据)
{
节点* addedNode =(节点*)malloc的(的sizeof(节点));
addedNode->数据=数据;
addedNode->链接=(开始== NULL)NULL:启动;
开始= addedNode;
}无效displayNodes(节点*开始)
{
节点* startCopy =启动;
而(startCopy!= NULL)
{
的printf(%d个\\ t的,startCopy->数据);
startCopy = startCopy->链接;
}
的printf(\\ n);
}诠释的main()
{
节点*开始= createList(2);
addAtBegin(启动,1);
displayNodes(开始);
返回0;
}
解决方案
看起来像另一个列表的问题对我来说,用同样的答案,因为他们大多 - 开始应该是一个指针的指针
What is wrong with addAtBegin
? The list seems to be correct after assigning the newly created node
to start
, but when control returns to main
, the new value is not saved.
typedef struct node
{
int data;
struct node *link;
}node;
node* createList(int data)
{
node *tempNode=(node*)malloc(sizeof(node));
tempNode->data=data;
tempNode->link=NULL;
return tempNode;
}
void addAtBegin(node *start,int data)
{
node *addedNode=(node *)malloc(sizeof(node));
addedNode->data=data;
addedNode->link=(start==NULL)?NULL:start;
start=addedNode;
}
void displayNodes(node *start)
{
node *startCopy=start;
while(startCopy!=NULL)
{
printf("%d\t",startCopy->data);
startCopy=startCopy->link;
}
printf("\n");
}
int main( )
{
node *start=createList(2);
addAtBegin(start,1);
displayNodes(start);
return 0;
}
解决方案
Looks like another list question to me, with the same answer as most of them - start should be a pointer to a pointer.
这篇关于如何插入在链表的开始的节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文