1

我想通过节点的索引号(序列号)从链表中删除给定的节点。所以我试图在我的函数中做的是,首先我接受了用户输入的索引号。然后我使用了两个节点类型指针tempcurrent. 我开始遍历列表,current当节点的索引号与用户输入匹配时,我尝试删除该节点。到目前为止它是正确的。我面临删除逻辑的问题。这是我尝试过的代码:

void delete_node(struct node **start,int index_no)
{    
    int counter=0;
    struct node *temp, *current;

    temp=(struct node *)malloc(sizeof(struct node));
    current=(struct node *)malloc(sizeof(struct node));
    current=*start;

    while(current->next!=NULL)
    {
        counter++;
        if(counter==index_no)
        {
            temp= current->next;
            free(current);
            /*I guess some code is missing here. Help me finding the logic.*/
        }
        else
        {
            printf("\n The index number is invalid!!");
        }
    }
}

注释部分缺少删除逻辑。另外,我有一种感觉,这段代码不节省空间和时间。如果是这样,请建议一种使其更紧凑的方法。

4

2 回答 2

1

从链表中删除实际上是:

  • 找到指向我们的指针
  • (如果找到)让它指向我们的 .next 指针
  • 删除我们的节点。

为了改变指向我们的指针,我们需要一个指向它的指针:一个指向指针的指针。幸运的是,第一个参数已经是一个指向指针的指针,它可能指向指向第一个列表项的头指针。

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

void delete(struct node **pp, int num) {
    struct node *del;
    int counter;

    for (counter=0; *pp; pp= &(*pp)->next) {
        if(counter++ == num) break;
        }

    if (!*pp) { printf("Couldn't find the node(%d)\n", num); return; }

    /* if we get here, *pp points to the pointer that points to our current node */

    del = *pp;
    *pp = del->next;
    free(del);
  }
于 2013-09-11T19:28:06.097 回答
1

为什么要在删除函数中分配两个节点,然后泄漏它们的内存?似乎它们应该被初始化为start或其后继者之一。

如果删除的元素是第一个(即。 ) ,您还需要更新next前一个元素中的指针,并且可能还更新列表的(头)。startindex_no == 1

您还会遇到一个错误,即永远无法删除最终节点,因为只有带有->next指针的节点才会被考虑删除。

推荐阅读:C 中的指针和数组教程

于 2013-09-11T19:08:38.570 回答