【问题标题】:Deleting first node without head pointer in C在C中删除没有头指针的第一个节点
【发布时间】:2021-05-01 06:37:02
【问题描述】:

我正在尝试制作从第一个节点删除的链表代码。我创建了一个结构 a

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

然后添加一些节点,不使用头指针,这里是我的主要

int main(){
struct node *first = malloc(sizeof(struct node));
struct node *second = malloc(sizeof(struct node));
struct node *third = malloc(sizeof(struct node));
struct node *forth = malloc(sizeof(struct node));

first->data = 1; //assing data in first node
first -> next = second; // link first node with second node

second -> data = 2;
second -> next = third;

third -> data = 3;
third -> next = forth;

forth -> data = 4;
forth->next = NULL;

printList(first);

// deletefromBeg(first);

    //printList(first);

}

这是我打印列表的 printList 代码

void printList(struct node *n){
while (n != NULL){
    printf("%d\n",n->data);
    n = n -> next;
}
}

但是这个删除代码不起作用。我只想删除我的第一个节点,然后列表从第二个开始。

void deletefromBeg(struct node *first){
struct node *temp;
temp = first;
first = first->next;
printf("%d",temp->data);
free(temp);
}

【问题讨论】:

  • 您想要printList(second),因为first 不再是列表的一部分。但无论如何,我会写一个合适的 InsertListAppendList 或任何允许您将 en 元素正确添加到列表的函数,

标签: c pointers singly-linked-list pass-by-value function-definition


【解决方案1】:

函数首先通过值获取指针。这意味着该函数首先处理指针值的副本

void deletefromBeg(struct node *first){
struct node *temp;
temp = first;
first = first->next;
printf("%d",temp->data);
free(temp);
}

更改值的副本不会影响首先存储在指针中的原始值。

main中定义的指针first和函数的参数first是两个不同的对象。在函数中,您正在更改由 main 中定义的指针 first 的值的副本初始化的参数 first

你有两种方法。

要么你必须返回函数中获得的指针的新值,然后在 main 中首先将其分配给指针

struct node * deletefromBeg( struct node *first )
{
    if ( first != NULL )
    {
        struct node *temp = first;
        first = first->next;
        free( temp );
    }

    return first;
}

在 main 中你调用函数就像

first = deletefromBeg( first );

或者你应该先通过引用传递指针。在 C 中,通过引用传递对象意味着通过指向对象的指针间接传递对象。

void deletefromBeg( struct node **first )
{
    if ( *first != NULL )
    {
        struct node *temp = *first;
        *first = ( *first )->next;
        free( temp );
    }
}

在 main 中,函数被称为

deletefromBeg( &first );

【讨论】:

  • 我非常了解。非常感谢。
  • @Burakkepuc 完全没有。不客气。:)
【解决方案2】:

现在使用此删除功能,您可以删除第一个节点并从第二个开始列表。

void delete(struct node *first) {
*first = *first->next;
free(first);
}

【讨论】:

  • 这是不正确的,它将第二个节点复制到第一个节点上,然后删除第一个节点。此外,它需要在执行任何操作之前检查是否有第二个节点。
猜你喜欢
  • 2021-01-15
  • 2015-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多