gpt4 book ai didi

c - 删除功能中不需要的结果

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

当我尝试删除列表的第二个节点时,我得到的第一个元素等于零,而第二个节点没有改变我使用代码块版本 13.12...... .....................................................

#include <stdio.h>
#include <stdlib.h>

struct node
{
int data;
struct node * next;
};


struct node* Insert(struct node* head , int x)
{
struct node* temp = (struct node*)malloc(sizeof(struct node));
if(head == NULL) {

temp->data = x;
temp->next = NULL;
head = temp;
return head; }

temp->data = x;
temp->next = NULL;
struct node* temp1;
temp1 = head;
while(temp1->next != NULL) {

temp1= temp1->next;
}
temp1->next = temp;
return head;
}

struct node* Delete (struct node* head, int a)
{
struct node* temp1 = head;
if (a == 1)
head = temp1->next;
free (temp1);
return head;

for(int i = 0; i < a-2; i++)
temp1 = temp1->next;

struct node* temp2;
temp2 = temp1->next;
temp1->next = temp2->next;
free (temp2);
return head;

}







void print(struct node* head)
{

while(head != NULL)
{
printf("the data is %d \n", head->data);
head = head->next;
}

}


int main ()
{
struct node* root = NULL;
int a,c;
printf("How many numbers ? : \n");
scanf("%d",&a);
for(int i = 0; i<a; i++)
{
printf("Enter a number:\n");
scanf("%d",&c);
root = Insert(root, c);
}
Delete(root, 2);
print(root);
return 0;
}

最佳答案

我在您的代码中发现了两个错误。第一个是在函数 Delete

中不包含代码块
if (a == 1)
head = temp1->next;
free (temp1);
return head;

没有大括号,free (temp1); return head; 将始终执行。应该是

if (a == 1) {
head = temp1->next;
free (temp1);
return head;
}

第二个错误是没有将Delete 的返回值分配给root。应该是

root = Delete(root, 2);

改正这些后,它似乎可以正常运行。

关于c - 删除功能中不需要的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32768930/

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