C 删除函数中不需要的结果
当我尝试删除列表的第2个节点时,我得到的第一个元素等于零,第2个节点未更改,我使用代码块版本13.12C 删除函数中不需要的结果,c,codeblocks,C,Codeblocks,当我尝试删除列表的第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*)ma
#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;
}
#包括
#包括
结构节点
{
int数据;
结构节点*下一步;
};
结构节点*插入(结构节点*头,int x)
{
结构节点*temp=(结构节点*)malloc(sizeof(结构节点));
if(head==NULL){
温度->数据=x;
temp->next=NULL;
压头=温度;
返回头;}
温度->数据=x;
temp->next=NULL;
结构节点*temp1;
temp1=头部;
while(temp1->next!=NULL){
temp1=temp1->next;
}
temp1->next=temp;
回流头;
}
结构节点*删除(结构节点*头,int a)
{
结构节点*temp1=头部;
如果(a==1)
head=temp1->next;
免费(temp1);
回流头;
对于(int i=0;inext;
结构节点*temp2;
temp2=temp1->next;
temp1->next=temp2->next;
免费(临时2);
回流头;
}
无效打印(结构节点*头)
{
while(head!=NULL)
{
printf(“数据是%d\n”,head->data);
头部=头部->下一步;
}
}
int main()
{
结构节点*root=NULL;
int a,c;
printf(“多少个数字?:\n”);
scanf(“%d”和“&a”);
对于(int i=0;i我在您的代码中发现了两个错误。第一个错误是在函数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);
纠正这些错误后,它似乎运行正常。1)-->如果(a==1){head=temp1->next;free(temp1);return head;}
您没有将Delete
中的返回值分配给任何对象,例如root
,尽管我没有阅读任何细节。root=Delete(root,2);