当前位置: 代码迷 >> C语言 >> [求助]关于链表的问题
  详细解决方案

[求助]关于链表的问题

热度:140   发布时间:2006-03-21 18:27:00.0
[求助]关于链表的问题
/*函数作用:用带头节点的链表存储输入的字符窜并以‘!’结束,然后输入要删除的字符并输出该窜。*/
#include <malloc.h>
#include <stdio.h>
struct node
{
char ch;
struct node *next;
}
main()
{
void delete(struct node *p,char de);
char de;
int n=sizeof(struct node);
struct node *head,*ph;
printf("please input string end with \'!\':\n");
head=(struct node *)malloc(n); /*开辟头节点*/
ph=(struct node *)malloc(n);
head->next=ph;
while((ph->ch=getchar())!='!')
{ ph->next=(struct node *)malloc(n);
}
ph->next=Null;
printf("please input the letter you want to detele:");
scanf("%c",&de); /*输入要删除的字符*/
delete(head->next,de);
printf("\nthe changed string :%s\n",head->next);
getch();
}

void delete(struct node * p,char de)
{struct node * p1=p;
for(;p->ch;)
{if(p->ch==de)
{
p1=p->next;
free(p);
p1=p;
continue;
}
p=p->next;
}
free(p);
free(p1);
}
麻烦大家帮我看看错在哪里了,为什么输入后得不到正确结果。
当输入字符窜结束后还没有等我输入要删除的字符程序运行就结束了
----------------解决方案--------------------------------------------------------
struct node
{
char ch;
struct node *next;
}
后要加“;”

主程序总体很乱,建议将初始化,输入等都写成单独的函数,以便找错
----------------解决方案--------------------------------------------------------

/*函数作用:用带头节点的链表存储输入的字符窜并以‘!’结束,然后输入要删除的字符并输出该窜。*/
#include <malloc.h>
#include <stdio.h>
struct node
{
char ch;
struct node *next;
};
main()
{
void delete(struct node *p,char de);
char de;
int n=sizeof(struct node);
struct node *head,*ph,*q;
printf("please input string end with \'!\':\n");
head=(struct node *)malloc(n); /*开辟头节点*/
ph=(struct node *)malloc(n);
ph->ch=getchar();
head->next=ph;
q=ph;
while(ph->ch!='!')
{
ph=(struct node *)malloc(n);
ph->ch=getchar();
q->next=ph;
q=ph;

}
ph->next=NULL;
printf("please input the letter you want to detele:\n");
scanf("%c",&de);
scanf("%c",&de); /*输入要删除的字符*/
delete(head,de);
getch();
}

这样就可以了

void delete(struct node * p,char de)
{ struct node * p1,*r;
p1=r=p;
p1=p1->next;
while(p1->ch!=de)
{
r=p1;
p1=p1->next;
}
r->next=p1->next;

p1=p->next;
while(p1)
{
printf("%c",p1->ch);
p1=p1->next;
}
p1=p->next;
}


----------------解决方案--------------------------------------------------------

注意第一个 scanf("%c",&de); 存储的其实是回车符"\n",因为你输入'!'后按了回车键,自动存储"\n"


----------------解决方案--------------------------------------------------------
很值得注意输入时是否将\n计算在内的问题!
----------------解决方案--------------------------------------------------------

真是谢谢各位的帮助,这问题捆扰了我好长时间现在终于解决了!


----------------解决方案--------------------------------------------------------

但是你这段程序还是有很多错误阿 运行不了


----------------解决方案--------------------------------------------------------
  相关解决方案