首页 > 解决方案 > 从链表中删除节点的功能无法正常工作

问题描述

void del(struct node *l,int n) {
  struct node *temp1=(struct node*)malloc(sizeof(struct node));
  temp1=l;
  if (l==NULL) {
    printf("list already empty");
  }
  else if (n==1) {
    l=l->next;
    free(temp1);
  }
  else {
    struct node *temp2=(struct node*)malloc(sizeof(struct node));
    temp2=l;
    int i,j=1;
    while (i<(n-1)) {
      temp1=temp1->next;
      i++;
    }
    while (j<n) {
      temp2=temp2->next;
      j++;
    }
    temp1->next=temp2->next;
    free(temp2);
  }
}

所以这是我为从单链表中删除元素而编写的函数,但它没有提供所需的输出。有人可以帮帮我吗?

标签: clinked-listfreesingly-linked-listfunction-definition

解决方案


你的函数不正确。至少由于这些没有意义的内存分配,它会产生内存泄漏

struct node *temp1=(struct node*)malloc(sizeof(struct node));
struct node *temp2=(struct node*)malloc(sizeof(struct node));

第二个参数应该是无符号整数类型,并且列表中的位置应该从 0 开始。

该函数不应发出任何消息。由函数的调用者决定是否在调用函数后发出消息。

该函数可以通过以下方式定义

int del( struct node **head, size_t n ) 
{
    while ( *head != NULL && n-- )
    {
        head = &( *head )->next;
    }

    int success = *head != NULL;

    if ( success )
    {
        struct node *tmp = *head;
        *head = ( *head )->next;
        free( tmp );
    }

    return success;
}

如果在 main 中声明了一个指向头节点的指针,例如

struct node *head = NULL;

// filling the list

然后可以调用该函数,例如

size_t n = some_position;
del( &head, n );

或者

if ( del( &head, n ) )
{
    printf( "The node at position &zu is successfully deleted.\n", n );
}    

其中 n 是列表中的某个位置。


推荐阅读