调试程序,
并设计输入数据(如:bat,cat,eat,fat,hat,jat,lat,mat,#),测试程序的如下功能:不允许重复字符串的插入;根据输入的字符串,找到相应的结点并删除。
#include"stdio.h"
#include"string.h"
#include"stdlib.h"
#include"ctype.h"
typedef struct node
{
char data[10];
struct node *next;
}ListNode;
typedef ListNode * LinkList;
LinkList CreatListR1();
ListNode *LocateNode();
void DeleteList();
void printlist();
void DeleteAll();
//==========主函数==============
void main()
{
char *ch,*num;
LinkList head;
head=CreatListR1();
printlist(head);
printf(" Delete node (y/n):");
scanf("%s",num);
if(strcmp(num,"y")==0 || strcmp(num,"Y")==0){
printf("Please input Delete_data:");
scanf("%s",ch);
DeleteList(head,ch);
printlist(head);
}
DeleteAll(head);
}
//==========用尾插入法建立带头结点的单链表===========
LinkList CreatListR1(void)
{
char *ch;
LinkList head=(LinkList)malloc(sizeof(ListNode)); ListNode *s,*r,*pp;
r=head;
r->next=NULL;
printf("Input # to end ");
printf("Please input Node_data:");
scanf("%s",ch);
while(strcmp(ch,"#")!=0) {
pp=LocateNode(head,ch);
if(pp==NULL) {
s=(ListNode *)malloc(sizeof(ListNode));
strcpy(s->data,ch);
r->next=s;
r=s;
r->next=NULL;
}
printf("Input # to end ");
printf("Please input Node_data:");
scanf("%s",ch);
}
return head;
}
//==========按值查找结点,找到则返回该结点的位置,否则返回NULL==========
ListNode *LocateNode(LinkList head, char *key)
{
ListNode *p=head->next;
while(strcmp(p->data,key)!=0 && p)
p=p->next;
return p;
}
//==========删除带头结点的单链表中的指定结点=======
void DeleteList(LinkList head,char *key)
{
ListNode *p,*r,*q=head;
p=LocateNode(head,key);
if(p==NULL ) {
printf("position error");
exit(0);
}
while(q->next!=p)
q=q->next;
r=q->next;
q->next=r->next;
free(r);
}
//===========打印链表=======
void printlist(LinkList head)
{
ListNode *p=head->next;
while(p){
printf("%s, ",p->data);
p=p->next;
}
printf("\n");
}
//==========删除所有结点,释放空间===========
void DeleteAll(LinkList head)
{
ListNode *p=head,*r;
while(p->next){
r=p->next;
free(p);
p=r;
}
free(p);
}
参考答案:1.在main()中
char *ch, *num; 改为 char ch[10], num[10];
2.在CreateListR1()中
char *ch; 改为 char ch[10];
3.在LocateNode()中
while(strcmp(p->data,key)!=0 && p)改为
while(p && strcmp(p->data,key)!=0)
4.在DeleteList()中
exit(0); 改为 return;