gpt4 book ai didi

c++ - 用一个程序创建多个链表

转载 作者:行者123 更新时间:2023-11-30 20:26:45 27 4
gpt4 key购买 nike

我是链表新手,我正在尝试编写一个程序,我们可以简单地将新头传递给 add() 函数并创建我们想要的任意数量的列表。但不知何故,代码根本不起作用。从输出看来,每次我调用 add() 函数时,即使具有相同的头地址,也会创建一个新的头。

有人可以告诉我如何继续吗?

这是我写的:

#include<stdio.h>
#include<iostream>
using namespace std;

struct node
{
struct node *next;
int val;
};


void add(int i,node** h,node** e)
{
node* head = *h;
node* endnode = *e;
printf("adding\n");
if(head!=NULL)
{
node *n = (struct node*)malloc(sizeof(node));
n->next = NULL;
n->val = i;

endnode->next = n;
endnode = n;
}
else
{
printf("heading\n");
head = (struct node*)malloc(sizeof(node));
head->next = NULL;
head->val = i;
endnode = head;
}

}

void delete_node(int i,node** h,node** e)
{
node* head = *h;
node* endnode = *e;
node *temp;
node *n = head;
while(n!=NULL)
{
if(n->val == i)
{
if(n==head)
{
head = head->next;
}
else if(n==endnode)
{
temp->next = NULL;
endnode = temp;
}
else
{
temp->next = n->next;
}
free(n);
break;
}
else
{
temp = n;
n = n->next;
}
}
}

void display(node** h)
{
node* head = *h;

node *n = head;

while(n!=NULL)
{
printf("%d\n",n->val);
n = n->next;
}
}



int main()
{

node *head = NULL;
node *endnode = NULL;

add(5,&head,&endnode);
add(8,&head,&endnode);
add(1,&head,&endnode);
add(78,&head,&endnode);
add(0,&head,&endnode);

display(&head);
printf("\n\n");

system("pause");
return 0;

}

最佳答案

除了设计之外,直接回答你的问题,问题是:

  1. 在 main() 中创建一个指针

    node *head  = NULL;
  2. 您将其地址传递给函数,从而获得一个指向指针的指针

    void add(int i,node** h,node** e)
  3. 您取消引用它,从而在外部获得精确的指针

    node* head = *h;
  4. 您将分配给指针的本地拷贝

    head  = (struct node*)malloc(sizeof(node));
  5. 您继续高兴地认为您已经更新了我在 1 中列出的指针。

作为个人观点,我同意这些评论:您可以使用更简洁的设计而不是那些双指针。

<小时/>

编辑:为了帮助您理解,这是具有您确切设计的正确版本

void add(int i,node** h,node** e)
{
printf("adding\n");
if(*h!=NULL)
{
node *n = (struct node*)malloc(sizeof(node));
n->next = NULL;
n->val = i;

(*e)->next = n;
*e = n;
}
else
{
printf("heading\n");
*h = (struct node*)malloc(sizeof(node));
(*h)->next = NULL;
(*h)->val = i;
*e = *h;
}

}

在您的第一个版本中,您正在这样做(伪代码):

void functon(int** ptrToPtrToInt) {
int* ptrToInt = *ptrToPtrToInt; // suppose ptrToInt now contains 0x20 (the address of the integer)
ptrToInt = malloc(sizeof(int)); // ptrToInt loses the 0x20 and gets a new address
} // ptrToInt gets destroyed, but nobody updated the pointer where ptrToPtrToInt came from, thus is unchanged

关于c++ - 用一个程序创建多个链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24354026/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com