C语言程序设计练习之链表--数据库/实现录入,删除和添加
#include<stdio.h>#include<stdlib.h>
#include<iostream>
#include<cmath>
#include<math.h>
#include<string.h>
#define LEN sizeof(struct man)
struct man
{
int num;
float score;
struct man* next;
};
struct man* creat();
struct man* deletes(struct man *head);
struct man *adds(struct man* head,struct man *stu);
void prints(struct man* head);
int main()
{
struct man* trans, * transs, * transss;
trans = creat();
prints(trans);
int i = 0;
for (;;)
{
printf("if you wanna delete a data please enter 1,if wanna add a data enter 2,leave enter 3\n");
scanf_s("%d", &i);
if (1 == i)
{
transs = deletes(trans);
prints(transs);
trans = transs;
}
if (2 == i)
{
struct man stu;
printf("please enter num to add:\n");
scanf_s("%d", &stu.num);
printf("please enter a score for num:%d\n", stu.num);
scanf_s("%f", &stu.score);
transss = adds(trans,&stu);
prints(transss);
trans = transss;
}
if (3 == i)
{
break;
}
}
system("pause");
return 0;
}
int n;
//struct man* head;
struct man* creat()
{
struct man* head;
struct man* p1, * p2;
p1 = p2 = (struct man*)malloc(LEN);
printf("please enter a num:\n");
scanf_s("%d", &p1->num);
printf("please enter score\n");
scanf_s("%f", &p1->score);
head = NULL;
n = 0;
while (p1->num)
{
n = n + 1;
if (1 == n)
{
head = p1;
}
else
{
p2->next = p1;
}
p2 = p1;
p1 = (struct man*)malloc(LEN);
printf("please enter a num\n");
scanf_s("%d", &p1->num);
printf("please enter a score:\n");
scanf_s("%f", &p1->score);
}
p2->next = NULL;
return (head);
}
void prints(struct man* head)
{
//struct man* p;
//p = head;
if (head == NULL)
{
printf("sorry this a null list.\n");
}
printf("record:%d\n\n", n);
do
{
printf("num:%d, score:%f\n", head->num, head->score);
head =head->next;
} while (head);
printf("print succeed!thank for using\n\n");
}
struct man* deletes(struct man *head)
{
struct man* p1, * p2;
p1 = p2 = head;
int j = 0;
printf("please enter serial num to delete:\n");
//getchar();
scanf_s("%d", &j);
while (p1->num != j && p1->next != NULL)
{
p2 = p1;
p1 = p1->next;
}
if (head == NULL)
{
goto END;
}
if (p1->num == j)
{
if (p1 == head)
{
head = p1->next;
}
else
{
p2->next = p1->next;
}
printf("delete succeed.\n\n");
n = n - 1;
}
else
{
printf("no found data to delete\n\n");
}
END:
return (head);
}
struct man *adds(struct man* head, struct man *stu)
{
struct man* p0, * p1, * p2;
//p0 = stu;
p0 = (struct man*)malloc(LEN);
*p0 = *stu;
p2=p1 = head;
if (NULL == head)
{
head = p0;
p0->next = NULL;
}
else
{
while ((p0->num > p1->num) && (p1->next != NULL))
{
p2 = p1;
p1 = p1->next;
}
if (p0->num <= p1->num)
{
if (head == p1)
{
head = p0;
}
else
{
p2->next = p0;
}
p0->next = p1;
}
else
{
p1->next = p0;
p0->next = NULL;
}
}
n = n + 1;
return (head);
}😁
页:
[1]