当我尝试删除列表的第2个节点时,我得到了第一个元素等于零而第2个节点没有使用代码块版本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;
}
答案 0 :(得分:2)
我在你的代码中发现了两个错误。第一个不支持函数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);
纠正后,它似乎运行正常。