本帖最后由 mingcxx 于 2016-9-12 20:41 编辑
感觉你的代码思路有点乱,
创建节点时从第2个节点开始录入数据,整个程序运行中头结点数据一直是不定内存,浪费内存。
删除节点时却只释放了节点所占用的内存(而没有把待删除节点的前一个节点中指向该节点的Next指针更新NULL或指向目标节点的下一节点),那你的链表中依然链接了这个节点,只不过释放内存之后,这个节点的内存不可读。p = p->pNext;自然要出错。
以及没有释放链表占用的内存。
下面是仅仅无bug的修改代码,输出的数据意义不清晰(尤其第3行),依赖具体功能和代码思路需要进一步修改:#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
//函数声明
struct NODE1
{
int data;
struct NODE1 * pNext;
};
typedef struct NODE1 NODE;
//typedef struct NODE1 * PNODE;
NODE * creat_list();
int length_list(NODE * pHead);
void delete_list(NODE * pHead, NODE ** p);
int main()
{
NODE * pHead = creat_list();
int count = 0;
NODE * p = pHead;
while (length_list(pHead)>1)
{
p = p->pNext;
++count;
if (count == 3 && p != NULL)
{
delete_list(pHead, &p);
count = 0;
}
if (p == NULL)
{
p = pHead;
}
if (count < 3)
break;
}
printf("剩余的人的编号是:%d", pHead->pNext->data);
while (1);
return 0;
}
NODE * creat_list()
{
NODE * pHead = (NODE *)malloc(sizeof(NODE));
int len, data, i;
NODE * pTail;
printf("一共多少人玩(请输入人数):\n");
scanf_s("%d", &len);
if (pHead == NULL)
{
printf("分配内存失败,程序结束!");
exit(-1);
}
pHead->pNext = NULL;
pTail = pHead;
for (i = 0; i<len; i++)
{
NODE * pNew = (NODE *)malloc(sizeof(NODE));
if (pNew == NULL)
{
printf("分配内存失败,程序结束!");
exit(-1);
}
pNew->pNext = NULL;
pNew->data = i + 1;
printf("%d", pNew->data);
pTail->pNext = pNew;
pTail = pNew;
}
printf("\n%d", pHead->pNext->data);
return pHead;
}
int length_list(NODE * pHead)
{
int len = 0;
NODE * p = pHead->pNext;
while (p != NULL)
{
len++;
printf("%d", len);
p = p->pNext;
}
printf("%d", len);
return len;
}
void delete_list(NODE * pHead, NODE ** p)
{
//if (pHead->pNext == NULL)
// return false;
NODE * pTag = pHead; NODE * pFore = pHead;
while (pTag->pNext != *p)
{
pFore = pTag;
pTag = pTag->pNext;
}
if ((*p)->pNext != NULL)
{
pTag->pNext= (*p)->pNext;
}
else
pTag->pNext = NULL;
free((*p));
*p = NULL;
//return true;
}
|