能帮我看一下函数错哪里了吗,每一次都会进入add函数中的if(phear->next==0)可是第一次又改变啊

秃头笔记 2017-01-08 10:52:00
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node1
{
char name[20];
char number[20];
struct node1 * next;
}node;
void add(node *phear, node *ptail, char name[20], char numder[20]);
void rmall(node *phear, node *ptail);
void rm(node *phear, char name[20], node *ptail);
void traver(node *phear, char name[20], node *ptail);
void traveral(node *phear, node * ptail);
int main()
{
int a;
node * phear = (node*)malloc(sizeof(node));
phear->next = 0;
node * ptail = phear;
add(phear, ptail, "陈泽键", "15625776360");
add(phear, ptail, "吴和津", "15629298978");
add(phear, ptail, "张志森", "15623434978");
traveral(phear, ptail);
scanf_s("%d", &a);
switch (a)
{
case 1: rmall(phear, ptail);break;
case 2: rm(phear, "吴和津", ptail);
system("pause");
return 0;
}
}
void add(node *phear, node *ptail, char name[20], char number[20])
{
node * newnode = (node*)malloc(sizeof(node));

if (newnode == 0)
{
printf("新节点分配失败\n");
return ;
}
strcpy_s(newnode->name,name);
strcpy_s(newnode->number,number);
if (phear->next == 0)
{
phear = ptail = newnode;
phear->next = newnode;
getchar();
}
else
{
newnode->next = phear->next;
phear = newnode;

}
}

void rmall(node *phear,node *ptail)
{
node*p = phear;
while (p != ptail)
{
free(p);
p = phear->next;
}
}
void rm(node *phear, char name[20], node *ptail)//搜索名字删除
{
node *p = phear;
while (p != ptail)
{
if(p->next->name==name)
break;
p = p->next;
}
p->next = p->next->next;
free(p);
}
void traver(node *phear, char name[20], node *ptail)
{
node *p = phear;
while (p != ptail)
{
if(p->name==name)
{
printf("联系人%s的电话号码是%s\n", p->name, p->number);
break;
}
}
}
void traveral(node *phear, node * ptail)
{
node *p = phear;

while (p != ptail)
{
printf("联系人%s的电话号码是%s\n", p->name, p->number);
p = p->next;
}
printf("联系人%s的电话号码是%s\n", p->name, p->number);
}
...全文
241 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
小灸舞 版主 2017-01-09
  • 打赏
  • 举报
回复
不明白你add函数里写的: if (phear->next == 0) { phear = ptail = newnode; phear->next = newnode; getchar(); } 这样写根本不对。 楼上写的思路是对的,但是ptail = newnode;是没有用的,在函数内要想改变指针的指向,必须传二级指针或者一级指针的引用才行
like_tortoise 2017-01-08
  • 打赏
  • 举报
回复
单链表保持一个数据项为null的头节点,在链表头插入节点: if (phear->next == NULL){  //链表空 phead->next = newnode; ptail = newnode; newnode->next = NULL; } else { //链表非空 newnode->next = phead->next; phead->next = newnode; }

69,369

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧