解决了
通过在添加新节点后将头部复制到另一个变量中也可以解决该问题。正如答案所说,更合乎逻辑的解决方案就是做。
我正在练习一个简单的链表实现,想要更多地探索指针。为什么我的代码没有正确添加节点?
typedef struct Node{
int info;
struct Node* next;
}Node;
void createList(Node** node, int info){
*node = calloc(1, sizeof(Node));
(*node)->info = info;
(*node)->next = NULL;
}
Node* newNode(int info)
{
Node* newNode;
newNode = calloc(1, sizeof(Node));
newNode->info = info;
newNode->next = NULL;
return newNode;
}
void addNode(Node** node, int info){
int adaugat = 0;
if(*node == NULL){
createList(node, info);
adaugat = 1;
}
if(adaugat == 0)
{
Node **aux = node;
while((*aux)->next != NULL)
{
*aux = (*aux)->next;
}
(*aux)->next = newNode(info);
adaugat = 1;
}
}
void printList(Node* node){
int i = 1;
Node* aux;
aux = node;
while(aux != NULL)
{
printf("%d_[%d]--",i, aux->info );
i++;
aux = aux->next;
}
}
int main(int argc, char const *argv[])
{
Node *nod = NULL;
int key = 5;
createList(&nod, key);
addNode(&nod, 5);
addNode(&nod, 3);
addNode(&nod, 4);
addNode(&nod, 1);
printList(nod);
return 0;
}
我试图在main()中调用指针和函数调用输入,但我得到的更多是警告和段错误。 main()的输出是1_[4]--2_[1]--
应该是的
1_[5]--2_[3]--3_[4]--4_[1]--
在这个功能addNode
的片段
if(adaugat == 0)
{
Node **aux = node;
while((*aux)->next != NULL)
{
*aux = (*aux)->next;
}
(*aux)->next = newNode(info);
adaugat = 1;
}
更确切地说,在*aux = (*aux)->next;
线上,由于Node ** aux
,你正在移动列表,同时你正在通过它。因此,它总是看起来像你的列表有两个元素。
如果要在列表末尾添加元素,则必须遍历列表而不进行修改,即
if(adaugat == 0)
{
Node *aux = *node;
while(aux->next != NULL)
{
aux = aux->next;
}
aux->next = newNode(info);
adaugat = 1;
}
问题在于以下代码块
if(adaugat == 0)
{
Node **aux = node;
while((*aux)->next != NULL)
{
*aux = (*aux)->next;
}
(*aux)->next = newNode(info);
adaugat = 1;
}
变量node
没有被解除引用,并且在这里使用双指针是不必要的。将该部分更改为以下内容将为您提供所需的输出...
if(adaugat == 0)
{
Node *aux = *node;
while(aux->next != NULL)
{
aux = aux->next;
}
aux->next = newNode(info);
adaugat = 1;
}
希望这可以帮助。