#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> typedef int DATA; struct SNode { DATA data;//数据 SNode*pNext;//指针区域 }; SNode*p_gHead = NULL; void AddHead(DATA data)//头曾 { SNode*p = (SNode*)malloc(sizeof(SNode)); p->data = data; p->pNext = p_gHead; p_gHead = p; } void Print()//大印 { SNode* p = p_gHead; while (p) { printf("%d ", p->data); p = p->pNext; } } void AddList(DATA data)//尾曾 { SNode *p = p_gHead; while (p->pNext != NULL) p = p->pNext; SNode*pNew = (SNode*)malloc(sizeof(SNode)); pNew->data = data; pNew->pNext = NULL; p->pNext=pNew; } void modif(DATA data, DATA dat)//链表修改 { SNode*p = p_gHead; while (p) { if (p->data == data) { p->data = dat; break; } p=p->pNext; } } /*--*/ int Delete(DATA data)//需要改错的地方 { SNode *p = p_gHead; while (p) { if (p->data == data) { free(p); return 1; } p = p->pNext; } return 0; } /*--*/ int main() { AddHead(3); AddHead(2); AddHead(1); Print(); printf("\n"); modif(2, -888); Print(); printf("\n"); int i=Delete(-888); Print(); return 0; }
以下是本人对int Delete(DATA data)的修改
int Delete(DATA data)//需要改错的地方 { SNode *p = p_gHead; SNode* deltemp;//声明一个临时结构变量,用来存作储要删除的节点 deltemp=(SNode*)malloc(sizeof(SNode));//初始化 int i=0,j=0; while (p)//遍历链表,获得要删除的节点 { if(p->data==data) { break; } p = p->pNext; ++i; //得到要删除的节点 } while(j<i-1) //循环到要删除的前一个节点 { p=p->pNext; ++j; } deltemp=p;//临时指针域保存要删除的节点 p=p->pNext;//指向下一个节点 free(deltemp);//删除指定的节点 return 1; }
主函数中是要删除-888的。结果却报错了。想问一下各位前辈,本人已经循环到要删除的节点,并且把要删除的节点放到一个临时的变量,原来要删除的节点指向了下一个节点。为什么会报错?
报错图如下
解决方案
100
用一个pre指针记录当前结点的前一个结点的地址,然后找到要删除的结点后,让pre->pNext指向p的后一个结点就行了(这里要考虑假如删除的是第一个结点,需要执行的应该是p_gHead = p->pNext)
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> typedef int DATA; struct SNode { DATA data;//数据 SNode*pNext;//指针区域 }; SNode*p_gHead = NULL; void AddHead(DATA data)//头曾 { SNode*p = (SNode*)malloc(sizeof(SNode)); p->data = data; p->pNext = p_gHead; p_gHead = p; } void Print()//大印 { SNode* p = p_gHead; while (p) { printf("%d ", p->data); p = p->pNext; } } void AddList(DATA data)//尾曾 { SNode *p = p_gHead; while (p->pNext != NULL) p = p->pNext; SNode*pNew = (SNode*)malloc(sizeof(SNode)); pNew->data = data; pNew->pNext = NULL; p->pNext = pNew; } void modif(DATA data, DATA dat)//链表修改 { SNode*p = p_gHead; while (p) { if (p->data == data) { p->data = dat; break; } p = p->pNext; } } /*--*/ int Delete(DATA data)//需要改错的地方 { SNode *p = p_gHead, *deltemp, *pre = p_gHead; while (p) { if (p->data == data) { deltemp = p; if (deltemp == p_gHead)//删除的是第一个结点 p_gHead = p->pNext; else pre->pNext = p->pNext; free(deltemp); return 1; } pre = p; p = p->pNext; } return 0; } /*--*/ int main() { AddHead(3); AddHead(2); AddHead(1); Print(); printf("\n"); modif(2, -888); Print(); printf("\n"); int i = Delete(-888); Print(); return 0; }