修改了的链表建立和插入怎么还运行不了

来源:百度知道 编辑:UC知道 时间:2024/06/10 01:32:36
下面是根据上个问题经高手指点后修改了的一个建立字符串的链表,然后在第i个位置插入一个字符,程序在 Dev-C++环境下运行,可却还是运行不了,请哪位高手再指点一下,看那面那程序哪儿行不通,只要能运行通过(一定要能运行通过),可以大幅度修改,但别改变程序的主意(建字符表,然后在随意第 i 个位子随意插入什么字符)。谢谢了!急!
#include <stdio.h>
#include <malloc.h>
typedef struct JD
{char data;
struct JD *next;}JD;
JD *creatlist()
{
char ch;
JD *head,*s;
head=NULL;
ch=getchar();
while(ch!='#')
{
s=(JD *)malloc(sizeof(JD));
s->data=ch;
s->next=head;
head=s;
ch=getchar();
}
fflush(stdin);
return head;
}
JD *Insert(JD*head,int i,char e)
{
JD *p,*s;
int j;
p=head;
j=0;
while(p&&j<i-1)
{
p=p->next;
++j;
}
if(p&&j<=i-1)
{
s=(JD *)malloc(sizeof(JD));
s->data=e;
s->next=p->next;
p->next=s;
}
return head;
}
void print(JD *head)
{
JD *p;
printf("the ch

这个程序可以在DEV-C++中正常插入元素,并输出结果,只不过原程序不能在顶部插入元素,为此将Insert()函数修改如下,在DEV-C++4992中测试正常:

JD *Insert(JD*head,int i,char e)/*在链表head中第i个元素之后插入数据成员为e的新元素*/
{
JD *p,*s;
int j;
p=head;
j=0;
while(p&&j<i-1)
{
p=p->next;
++j;
}
if (!i){/*注意这里*/
s=(JD *)malloc(sizeof(JD));
s->data=e;
s->next=head;
head=s;
}
else if(p&&j<=i-1)/*注意这里*/
{
s=(JD *)malloc(sizeof(JD));
s->data=e;
s->next=p->next;
p->next=s;
}
return head;
}

*******************************************

恕我直言,网友zhaojingyun120的修改有些多此一举,原程序只有Insert()函数有问题,其它部分都正常,无需画蛇添足。

修改了creatlist()里的输入语句.原先的语句把很多回车符也当作你输入的字符放进链表里了.去掉fflush().
修改了insert()函数的大部分
#include <stdio.h>
#include <malloc.h>
typedef struct JD
{char data;
struct JD *next;}JD;
JD *creatlist()
{
char ch;
JD *head,*s;