我正试图从Singly Linked List中删除,但当我试图从第一个元素中删除时,它会打印垃圾。我认为问题来自delete_node函数,然而,我尝试了所有的方法,但都无法解决。
#include <stdio.h>//prinf
#include <stdlib.h>//alloc mallco callo
typedef struct node node;
struct node{
int number;
node *next;
};
node *new_node(int num){
node *n= (node*) malloc(sizeof(node));
n->number=num;
n->next=NULL;
return n;
}
void node_free_all(node *n){
if(n != NULL){
node_free_all(n->next);
free(n);
}
}
void print_nodes(node *n){
if(n != NULL){
print_nodes(n->next);
printf("Number is: %dn",n->number);
}
}
void delete_node(node *n, int num){
node *rmNode= (node*)malloc(sizeof(node));
//delete first
if( n!= NULL && n->number==num){
rmNode = n;
n=n->next;
free(rmNode);
}
//all but first
while(n != NULL){
if(n->next != NULL && n->next->number == num){
rmNode= n->next;
n->next = rmNode->next;
free(rmNode);
break;
}
n=n->next;
}
}
int main(){
int i;
node *head= (node*) malloc(sizeof(node));
node *curr;
head=NULL;
for(i=1;i<=10;i++) {
curr = new_node(i);
curr->next =head;
head=curr;
}
printf("Everything:n");
print_nodes(head);
printf("Deleting 1:n");
delete_node(head,1);
print_nodes(head);
printf("Deleting 5:n");
delete_node(head,5);
print_nodes(head);
printf("Deleting 2:n");
delete_node(head,2);
print_nodes(head);
printf("Deleting 3:n");
delete_node(head,3);
print_nodes(head);
printf("Deleting 10:n");
delete_node(head,10);
print_nodes(head);
printf("Deleting 9:n");
delete_node(head,9);
print_nodes(head);
node_free_all(head);
// node_free_all(list);
return 0;
}
我做错了什么?
您不需要为rmNode
分配内存。另外,您需要将head指针的引用传递给函数delete_node
,因为每次更新列表时,如果您必须删除列表的第一个元素,那么在这种情况下,head指针也会被更新。
struct node
{
int number;
node *next;
};
void delete_node(struct node** head_ref, int num)
{
struct node* temp;
struct node* current = (*head_ref);
//delete first
if( current != NULL && current->number == num)
{
temp = current;
current = current->next;
free(temp);
(*head_ref) = current;
}
else
{
//all but first
while(current != NULL)
{
if(current->next != NULL && current->next->number == num)
{
temp = current->next;
current->next = temp->next;
free(temp);
break;
}
current = current->next;
}
}
}
这里有一个版本,它删除了所有与num
匹配的项,并始终更新头项。
void delete_node(node** head_ref, int num)
{
node* temp;
node* last = 0;
node* current = *head_ref;
while(current)
{
if( current->number == num )
{
temp = current;
if( current == *head_ref )
current = (*head_ref) = current->next;
else
current = last->next = current->next;
free(temp);
} else {
last = current;
current = current->next;
}
}
}
你必须称之为delete_node(&head,1);
因为它需要一个标题项的地址才能将其更改为