【发布时间】:2020-04-01 02:06:17
【问题描述】:
当我在控制台上按顺序插入节点时,节点被插入
如何确保我处理所有边界条件?例如,如果用户输入的位置大于列表的大小怎么办?另外,当我尝试在 after 一个节点插入时遇到分段错误,但它在 before 一个节点上工作得很好。这是一张有助于更好地解释我的问题的图片
另外,当我尝试在一个节点之后插入时,我遇到了分段错误,但它在之前一个节点工作得很好。
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node *next;
};
struct Node *head = NULL;
struct Node *insert(int x,int pos)
{
if(head == NULL)
{
struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = x;
temp->next = head;
head = temp;
return head;
}
else
{
int len = 0;
struct Node *temp = head;
while(temp!=NULL)
{
++len;
temp = temp->next;
}
if(pos == 1)
{
struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = x;
temp->next = head;
head = temp;
return head;
}
else
{
struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = x;
temp->next = NULL;
struct Node *temp1 = head;
for(int i = 2; i<pos; i++)
{
temp1 = temp1->next;
}
temp->next = temp1->next;
temp1->next= temp;
}
}
}
void print()
{
struct Node *temp = head;
while(temp!=NULL)
{
printf("%d ",temp->data);
temp = temp->next;
}
printf("\n");
}
int main()
{
int n,i,x,pos;
printf("How many elements?\n");
scanf("%d",&n);
for(i = 0; i<n; i++)
{
printf("enter the value and the position: \n");
scanf("%d %d",&x,&pos);
insert(x,pos);
print();
}
printf("Linked list is: \n");
print();
}
输出 1
How many elements?
3
enter the value and the position:
3 2
List is: 3
enter the value and the position:
4 3
Segmentation fault (core dumped)
输出 2
How many elements?
3
enter the value and the position:
3 2
List is: 3
enter the value and the position:
4 1
List is: 4 3
enter the value and the position:
5 3
List is: 4 3 5
Linked list is:
4 3 5
【问题讨论】:
-
请勿张贴文字图片。
-
尝试到处添加 NULL 检查...
-
@n.'pronouns'm。已编辑。
-
@dan1st 我不确定在哪里可以添加更多检查。是不是检查头指针是否为 NULL 或不足以进行插入操作?我在这里的输出似乎是矛盾的。我可以插入第 2、第 1 和第 3 个位置(按此顺序),但不能插入第 2、第 3 和第 1 个位置。请解释一下?
-
你应该在每个 malloc 之后添加空检查,
pos可能比列表大。
标签: c data-structures struct linked-list singly-linked-list