问题描述
- 大一狗遇到了一个问题,请大手帮忙看看!!!!
-
- #include
- #include
- #include
- struct Node
- {
- int num;
- char name[10];
- char sex;
- int phone_number;
- char addr[31];
- struct Node *pnext;
- struct Node *pfront;
- };
- struct Node * creat()
- {
- struct Node *head,*temp,*tail=0;
- int numtemp;
- printf("请输入编号姓名性别电话号码和住址,编号为0退出:n");
- scanf("%d",&numtemp);
- while(numtemp>0)
- {
- temp=(struct Node *)malloc(sizeof(struct Node));
- temp->num=numtemp;
- scanf("%s%c%d%s",temp->name,&temp->sex,&temp->phone_number,temp->addr);
- if(!head)
- {
- head=tail=temp;
- }
- else
- {
- tail->pnext=temp;
- temp->pfront=tail;
- tail=temp;
- }
- printf("请输入编号姓名性别电话号码和住址,编号为0退出n");
- scanf("%d",&numtemp);
- }
- return head;
- }
- void getin(struct Node *head)
- {
- struct Node *p;
- struct Node *temp=head;
- p=(struct Node *)malloc(sizeof(struct Node));
- printf("输入新添加联系人的编号姓名性别电话号码和住址");
- scanf("%d%s%c%d%s",&p->num,&p->name,&p->sex,&p->phone_number,&p->addr);
- while(temp->pnext!=NULL)
- {
- if((temp->num)>(p->num))
- {
- p->pfront=temp->pfront;
- temp->pfront->pnext=p;
- p->pnext=temp;
- temp->pfront=p;
- }
- else
- temp=temp->pnext;
- }
- if(p->pnext==NULL)
- {
- temp->pnext=p;
- p->pfront=temp;
- }
- }
- void put(struct Node * head)
- {
- struct Node *temp=head;
- while(temp->pnext!=NULL)
- {
- printf("%dt%st%ct%dt%st",temp->num,temp->name,temp->sex,temp->phone_number,temp->addr);
- temp=temp->pnext;
- printf("n");
- }
- printf("%dt%st%ct%dt%st",temp->num,temp->name,temp->sex,temp->phone_number,temp->addr);
- }
- struct Node * serch(struct Node *head,char *names)
- {
- while(head!=NULL)
- {
- if(strcmp(head->name,names)==0)
- return head;
- else
- head=head->pnext;
- }
- printf("没有找到相关联系人");
- return 0;
- }
- void dele(struct Node *head,char *names)
- {
- while(head!=NULL)
- {
- if(strcmp(head->name,names)==0)
- {
- head->pfront->pnext=head->pnext;
- head->pnext->pfront=head->pfront;
- free(head);
- break;
- }
- else
- head=head->pnext;
- }
- }
- int main()
- {
- struct Node *head;
- int n;
- char names[20];
- char names2[20];
- struct Node *p;
- printf("创建通讯录请输入1,插入输入2,删除输入3,输出输入4,查找输入5,退出输入0n");
- scanf("%d",&n);
- while(n!=0)
- {
- switch(n)
- {
- case 1:
- head=creat();
- break;
- case 2:
- getin(head);
- break;
- case 3:
- printf("请输入要删除的联系人姓名n");
- gets(names);
- dele(head,names);
- break;
- case 4:
- put(head);
- break;
- case 5:
- printf("请输入要查找联系人的姓名n");
- gets(names2);
- p=serch(head,names2);
- printf("%dt%st%ct%dt%s",p->num,p->name,p->sex,p->phone_number,p->addr);
- break;
- case 0:
- while(head!=NULL)
- {
- struct Node *p=head;
- head=head->pnext;
- free(p);
- }
- return 0;
- }
- }
- return 0;
- }
解决方案
代码太长了,直接说你遇到了什么问题吧。
解决方案二:
请输入编号姓名性别电话号码和住址,编号为0退出;
我输入了编号姓名性别,
程序就直接结束了,返回了一个乱七八糟的数
解决方案四:
p=(struct Node *)malloc(sizeof(struct Node));
只看到你分配了一次内存,后面循环都没有再分配过
解决方案五:
你先调试下,估计是内存分配问题,你仔细看下,我长期用C++,对C不熟了。最后直接说你遇到的问题,你这样提问题,也不好解决
解决方案六:
scanf的时候,格式加空格试试。 scanf("%s %c %d %s", ...)
看到没,那个%d、%c、%d、%s之间加上空格。
时间: 2024-09-17 03:29:55