解决指指针指向头节点进行free操作之后头节点丢失问题
发布时间:2023年12月18日
解决办法一:
在删除函数执行free(node)后,加上一句语句node = NULL
解决方法二:
传入参数的时候使用双重指针,如下图
调试代码如下,断点设置如下
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void insertNode(struct Node** head, int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
void deleteNodeWithData(Node **head, Node* nodeToDelete) {
if (nodeToDelete == NULL || *head == NULL) {
return;
}
if (*head == nodeToDelete) {
*head = nodeToDelete->next;
} else {
Node* current = *head;
while (current != NULL && current->next != nodeToDelete) {
current = current->next;
}
if (current != NULL) {
current->next = nodeToDelete->next;
}
}
free(nodeToDelete);
}
int main(){
struct Node* head = NULL;
struct Node* oddHead = NULL;
struct Node* evenHead = NULL;
int data;
while (1) {
scanf("%d", &data);
if (data == -1) {
break;
}
insertNode(&head, data);
}
Node *p;
p = head->next->next;
deleteNodeWithData(&head,p);
while(1){
printf("hellow");
}
}
文章来源:https://blog.csdn.net/hexinchaode/article/details/132756588
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:chenni525@qq.com进行投诉反馈,一经查实,立即删除!