gpt4 book ai didi

c - 单向链表操作在特定位置插入

转载 作者:太空宇宙 更新时间:2023-11-04 04:27:30 25 4
gpt4 key购买 nike

我编写了一个程序来执行单链表操作在特定位置插入 现在没有节点,当我给问题输入:3 输入要插入的位置显示运行时错误

void insert_pos()
{
struct node * temp, *loc;
int item,pos,len;
printf("enter the position to be insertd :");
scanf("%d", &pos);
if (pos == 1)
{
insert_beg();
}
else
{
len = length();
if (start == NULL)
{
insert_beg();
}
else if (pos > len)
{
insert_end();
}
else
{
newnode = (struct node *)malloc(sizeof(struct node));
printf("enter the data :");
scanf("%d", &item);
newnode->data = item;
int i;
temp = start;
loc = temp->next;
for (i = 1; i < pos - 1; i++)
{
temp = temp->next;
loc = loc->next;
}
temp->next = newnode;
newnode->next = loc;
}
}
}
int length()
{
int k = 1;
struct node * temp;
while (temp->next != NULL)
{
temp = temp->next;
k++;
}
return k;
}

输出

1.insert @ beg
2.insert @ end
3.insert @ perticular pos
4.display
5.exit
enter your option :3
enter the position to be inserted :3

现在弹出一个窗口说调试错误请帮助我

最佳答案

问题出在温度未初始化

int length()
{
int k = 1;
struct node * temp;
while (temp->next != NULL)
{
temp = temp->next;
k++;
}
return k;
}

解决方法是分配 temp = start;

更正程序

int length()
{
int k = 1;
struct node * temp;
temp=start; // start is a global variable
while (temp->next != NULL)
{
temp = temp->next;
k++;
}
return k;
}

感谢大家的提示!!!

关于c - 单向链表操作在特定位置插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40087916/

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