#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