如何解决删除C中没有头指针的第一个节点
我正在尝试制作从第一个节点中删除的链表代码。我创建了一个结构体
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);
}
解决方法
函数首先通过值获取指针。表示函数先处理指针值的副本
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 );
,
现在用这个删除函数删除第一个节点,列表第二个开始。
void delete(struct node *first) {
*first = *first->next;
free(first);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。