#define _CRT_SECURE_NO_WARNINGS 1
#include
#include
#include
#include
typedef int SListDataType;
typedef struct SListNode
{
SListDataType data;
struct SListNode* next;
}SListNode;
SListNode* CreatSListNode(SListDataType x)
{
SListNode* Newnode = (SListNode*)malloc(sizeof(SListNode));
if (Newnode == NULL)
{
printf("申请内存失败!");
exit(-1);
}
Newnode->data = x;
Newnode->next = NULL;
return Newnode;
}
//void InitSList(SListNode *L)
//{
// L = (SListNode*)malloc(sizeof(SListNode));
// L->data = 0;
// L->next = NULL;
//
//}
SListNode * InitSList()
{
SListNode* L = (SListNode*)malloc(sizeof(SListNode));
L->data = 0;
L->next = NULL;
return L;
}
void HeadInsertSList(SListNode* L,SListDataType x)
{
SListNode* Newnode = (SListNode*)malloc(sizeof(SListNode));
Newnode->data = x;
Newnode->next = L->next;
L->next = Newnode;
L->data++;
}
void TailInsertSList(SListNode* L, SListDataType x)
{
SListNode* p=CreatSListNode(x);
SListNode* cur = L;
while (cur->next != NULL)
{
cur = cur->next;
}
cur->next= p;
L->data++;
}
void EraseSList(SListNode* L, SListDataType x)
{
SListNode* pre = L;
SListNode* cur = L->next;
while (cur)
{
if (cur->data == x)
{
pre->next = cur->next;
free(cur);
}
pre = cur;
cur = cur->next;
}
}
void PrintSList(SListNode *L)
{
SListNode* p = L->next;
while (p!=NULL)
{
printf("%d->", p->data);
p = p->next;
}
printf("NULL");
}
int main()
{
SListNode* L=InitSList();
L->next = NULL;
L->data = 0;
InitSList(L);
HeadInsertSList(L, 1);
HeadInsertSList(L, 2);
HeadInsertSList(L, 3);
HeadInsertSList(L, 4);
TailInsertSList(L, 5);
TailInsertSList(L, 6);
TailInsertSList(L, 7);
TailInsertSList(L, 8);
EraseSList(L, 3);
PrintSList(L);
return 0;
}
显然L->next你没有设置为NULL
98行编译怎么通过的呢?
你的代码中,当找到值为x的结点后,调用了free(cur)
,那么cur就变成了野指针,之后再访问cur所指的内存就会崩溃。你可以改成如下形式
只删除第一个值为x的结点
while (cur && cur->data != x) {
pre = cur;
cur = cur->next;
}
pre->next = cur->next;
free(cur);
删除所有值为x的结点
while (cur)
{
if (cur->data == x)
{
SListNode *p = cur;
pre->next = cur->next;
cur = cur->next;
free(p);
}
else
{
pre = cur;
cur = cur->next;
}
}