不太会码的小猿 2022-05-09 20:45 采纳率: 100%
浏览 47
已结题

链表删除和查找问题 求解答

#include
#include<stdlib.h>
#include<string.h>
using namespace std;

struct student
{
char name[20];
int id;
int age;
char gender[20];
};
struct Node
{
student stu;
struct Node* next;
};
struct Node* init_list()
{
struct Node* head = (struct Node*)malloc(sizeof(struct Node));
head->next = NULL;
return head;
}
struct Node* creat_newNode(char* name,int id,int age,char* gender)
{
struct Node* Node = (struct Node*)malloc(sizeof(struct Node));
if (Node == NULL)
{
cout << "创建失败"<<endl;
return NULL;
}
Node->next = NULL;
strcpy_s(Node->stu.name, name);
Node->stu.id=id;
Node->stu.age = age;
strcpy_s(Node->stu.gender, gender);
return Node;
}
int insert_head(struct Nodehead,struct Node newNode)//头插法
{
if (head == NULL||NULL==newNode )
{
return -1;
}
newNode->next = head->next;
head->next = newNode;
}
int delete_list(struct Node
head,int id)
{
struct Node
p = head;
struct Node* q = head->next;
if (head == NULL)
{
return -1;
}
while (p->next!=NULL)
{
if (q->stu.id == id);
{ break;
}
p = p->next;
q = q->next;
}
if (p->next== NULL)
{
cout << "删除失败" << endl;
return -1;
}
p->next = q->next;
q->next = NULL;
free(q);
}

int find_list(struct Node* head,int id )//按学号查找学生
{
int i = 1;
struct Node* p = head;
if (p == NULL)
{
return -1;
}
while (p->next!=NULL&&p->stu.id!=id)
{
p = p->next;
++i;
}
cout << "第" << i << "找到该学生";
return 0;
}
int print_list(struct Node* head)
{
if (head == NULL)
{
return -1;
}
struct Node* p = head->next;
while (p!= NULL)
{
cout << p->stu.name << " " << p->stu.id <<" " << p->stu.age << " " << p->stu.gender << endl;
p = p ->next;
}
}
int main()
{
int id;
int i = 0;
int sum = 0;
struct student stu = { 0 };
struct Node* newNode = NULL;
struct Node* head = init_list();
cout << "学生个数" << endl;
cin >> sum;
cout << "请输入学生信息:" << endl;
for (i = 0; i < sum; i++)
{
cin >> stu.name >> stu.id >> stu.age >> stu.gender;
cout << endl;
newNode = creat_newNode(stu.name, stu.id,stu.age, stu.gender);
insert_head(head,newNode);
}
print_list(head);
cout << endl;
cout << "删除的学号:";
cin >> id;
cout << endl;
delete_list(head, id);
cout << "删除后" << endl;
//find_list(head, 2);
print_list(head);
return 0;
}
![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/295062001256111.jpg "#left

img

img

  • 写回答

1条回答 默认 最新

  • 心随而动 人工智能领域新星创作者 2022-05-09 22:02
    关注

    你描述一下你遇到的问题吧,比如你的要求,但以及想要的结果

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 5月10日
  • 已采纳回答 5月10日
  • 创建了问题 5月9日

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测