我写了一个程序来执行单链表操作insert at a particular position
现在没有节点,当我给输入:3时问题enter the position to be inserted
它显示运行时错误
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
现在弹出一个窗口说调试错误 请帮帮我吧
答案 0 :(得分:0)
问题在于这里的温度是未初始化的
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;
}
感谢每一位提示!