gpt4 book ai didi

c - c中的单链表插入方法终止

转载 作者:太空宇宙 更新时间:2023-11-04 06:55:35 24 4
gpt4 key购买 nike

void insert()
{
struct node *temp;
struct node *tmp;
int i;
int value;
int position;

temp = head;
printf("Enter a value to be inserted into the linked list");
scanf("%d", &value);
printf("Enter at which postion of the linked list to be added");
scanf("%d", &position);
printf("%d\t", position);
printf("%d\t", head);
printf("%d\t", temp);
printf("%d\t", value);

for (i = 1; i < position; i++)
{
temp = temp->next;
}

tmp->next = temp->next;
temp->next = (struct node *)malloc(sizeof(struct node));
temp->next->data = value;
temp->next->next = tmp->next;
}

这是我为单链表构建的插入函数,但它反过来又给我段错误。

最佳答案

如果要在单链表的头部插入一个新节点,那么必须先分配一个新节点并设置它的数据:

struct node *newNode;
newNode = (struct node *)malloc(sizeof(struct node));

然后链表的原始头部成为新节点的后继节点,新节点成为链表的新头部:

newNode->next = head;
head = newNode;

关于c - c中的单链表插入方法终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45389842/

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