C 在列表中插入节点的副本(带条件)
本练习要求插入值x的副本,该值也是要在列表中搜索的值,但前提是位置是另一个值n的倍数。未指定是在x值之前还是之后插入副本 我的问题是,并非所有情况下都插入副本。我认为问题在于,当我插入新节点时,列表位置的计数器也会计算这个新值,报告错误的结果 我怎样才能解决这个问题?还是我犯了一个错误 我在学习。也许我的尝试是完全错误的,出于这个原因,我要求至少有一个像样的解释,以便我可以改进 我的代码:C 在列表中插入节点的副本(带条件),c,list,insert,singly-linked-list,C,List,Insert,Singly Linked List,本练习要求插入值x的副本,该值也是要在列表中搜索的值,但前提是位置是另一个值n的倍数。未指定是在x值之前还是之后插入副本 我的问题是,并非所有情况下都插入副本。我认为问题在于,当我插入新节点时,列表位置的计数器也会计算这个新值,报告错误的结果 我怎样才能解决这个问题?还是我犯了一个错误 我在学习。也许我的尝试是完全错误的,出于这个原因,我要求至少有一个像样的解释,以便我可以改进 我的代码: struct data { int d; struct data *next; }
struct data
{
int d;
struct data *next;
};
typedef struct data Node;
Node *newnode(void)
{
return malloc(sizeof(Node));
}
Node *creat_list()
{
Node *lis, *p, *last;
int x;
printf("\n insert data: ");
scanf("%d", &x);
if(x <= 0)
{
lis = NULL;
}
else
{
last = newnode();
lis = last;
last->d = x;
last->next = NULL;
printf(" insert data: ");
scanf("%d", &x);
while(x > 0)
{
p = newnode();
p->d = x;
p->next = NULL;
last->next = p;
last = p;
printf(" insert data: ");
scanf("%d", &x);
}
}
return (lis);
}
void print_list(Node *lis)
{
printf("\n List: \n");
printf(" -> ");
while(lis != NULL)
{
printf("%d", lis->d);
printf(" -> ");
lis = lis->next;
}
printf("NULL\n\n");
}
void insertCopy(int x, int n, Node **lis)
{
int pos = 1;
Node *p, *head;
head = *lis;
if ((head->d == x) && (pos % n == 0))
{
p = newnode();
p->d = x;
p->next = head;
*lis = p;
}
if (head->next != NULL)
{
pos = 2;
while(head->next != NULL)
{
if ((head->next->d == x) && (pos % n == 0))
{
p = newnode();
p->d = x;
p->next = head->next;
head->next = p;
}
else
{
head = head->next;
}
pos++;
}
}
}
int main(void)
{
Node *l1;
int x = 1;
int n = 3;
l1 = creat_list();
print_list(l1);
insertCopy(x, n, &l1);
print_list(l1);
return 0;
}
给予
名单:
与
预期产出为:
2->3->1->1->6->1->2->2->6->1->1->5->NULL
2->3->1->1->6->1->2->2->6->1->5->NULL
我的输出是:
2->3->1->1->6->1->2->2->6->1->1->5->NULL
2->3->1->1->6->1->2->2->6->1->5->NULL
代码中有更多的问题,但是根据您的示例,您要求的问题是,您只得到一个额外的节点,而您需要两个额外的节点 预期:
2->3->1->1->6->1->2->2->6->1->1->5->NULL
实际:
2->3->1->1->6->1->2->2->6->1->5->NULL
^^^
A node is missing here
问题在于插入额外节点时处理头部的方式
尝试更改此选项:
if ((head->next->d == x) && (pos % n == 0))
{
p = newnode();
p->d = x;
p->next = head->next;
head->next = p;
}
进入
原始代码的问题是头部移动不正确。因此,计数器pos与原始列表不同步。@Sabaudian您的问题是,首先您只发布了预期输出,而没有发布实际输出。如果你一开始就把这两个都贴出来,我们就可以帮你了sooner@Sabaudian4386427所说的是正确的。如果你提供了一个像博多在第一次评论中所问的MRE,我们会注意到这一点,并在几分钟而不是几小时内给你一个答案。它以前被称为MCVE,你可以读到@Sabaudian的重要性,你会惊讶地发现,创建MRE的过程有多少次让我没有提出问题,因为正是这个过程让我意识到了解决方案。这确实是一个非常好的调试工具;这段对话已经结束。
if ((head->next->d == x) && (pos % n == 0))
{
p = newnode();
p->d = x;
p->next = head->next;
head->next = p;
}
if ((head->next->d == x) && (pos % n == 0))
{
p = newnode();
p->d = x;
p->next = head->next;
head->next = p;
head=p->next; // Add this line
}