发现cfree里链表代码可以运行,但是提交到平台发现内存错误,救命啊!
要求:
输入一系列字符以-#作为结束标志,用尾插法创建链表并存储数据,然后在指定位置删除一个新的字符,并输出结果
输入
第一行输入一一个字符串,以#结束
一个整数p
输出
链表所有数据(删除前、删除后)各占一行
样例输入
abcde#
2
样例输出
a b c d e
a c d e
#include"stdio.h"
#include"stdlib.h"
typedef struct node{
char data;
struct node *next;
}Node;
Node * creatlink();
void Dellink(Node *h,int p);
void output(Node *h);
void destroylink(Node *h);
main()
{
Node *head=NULL;
int p;
head = creatlink();
scanf("%d",&p);
output(head);
Dellink(head,p);
output(head);
destroylink(head);
}
Node * creatlink()
{
Node *head=NULL,*p,*q;
char ch;
head=(Node *)malloc(sizeof(Node)); //创建头结点,不存放有效数据
head->next=NULL;
q=head;
while(1) //创建链表
{
scanf("%c",&ch);
if(ch!='#'){
p = (struct node*)malloc(sizeof(struct node));
p -> data = ch;
p -> next = NULL;
q -> next = p;
q = p;
}
else
break;
}
return head;
}
void Dellink(Node *h,int p){
Node *pfront,*pafter,*q;
pfront=h;
pafter=h;
int i;
for(i=0;i<p-1;i++){
q = pfront->next;
pfront = q;
}
for(i=0;i<p+1;i++){
q = pafter->next;
pafter = q;
}
pfront->next = pafter;
}
void output(Node *h){
Node *p ;
p=h->next;
while(p){
printf("%c ",p->data);
p=p->next;
}
printf("\n");
}
void destroylink(Node *h){
Node *q;
while(h!=NULL)
{
q=h;
h=h->next;
free(q);
}
}
cfree:无
校园OJ平台:Runtime Error:Segmentation fault
这不是内存超限,这是段错误
for(i=0;i<p+1;i++){
q = pafter->next;
pafter = q;
}
这个是有风险的,如果删除的是最后一个节点呢,它是没有after的啊,最后一个pafter->next会崩溃的。你应该检查一下pafter是否为空。如果为空表示要删除的是最后一个节点,直接让pfront->next = NULL好了。
另外,被删除的节点你也应该free掉才符合你这段代码的风格