|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 veer786 于 2013-10-22 20:37 编辑
本帖最后由 veer786 于 2013-10-22 19:55 编辑
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define LEN sizeof(struct Student)//结构体的长度
int n;//全局变量,用来记录学生数
struct Student *creat();//创建链表
void print(struct Student *);//打印链表
struct Student* insert_link(struct Student *head,int num);//插入节点
struct Student //创建学生
{
int num;
int score;
struct Student *next;
};
int main()
{
struct Student *stu;
int num = 0;
stu = creat();
print(stu);
printf("请选择插入点\n");
scanf("%d",&num);
printf("在%d学生之后插入\n",num);
print(insert_link(stu,num));
return 0;
}
struct Student* creat()
{
struct Student *head = NULL;
struct Student *p1,*p2;
p1 = p2 = (struct Student *)malloc(LEN);
printf("请输入学号:\n");
while(scanf("%d",&p1->num) != 1)//用来检测错误输入
{
printf("输入有误,请重新输入学号!\n");
getchar();
}
printf("请输入分数:\n");
while(scanf("%d",&p1->score) != 1)//用来检测错误输入
{
printf("输入有误,请重新输入分数!\n");
getchar();
}
while(p1->num != 0)
{
n++;
if(n == 1)
{
head = p1;
}
else
{
p2->next = p1;
}
p2 = p1;
p1 = (struct Student *)malloc(LEN);
printf("请输入学号:\n");
while(scanf("%d",&p1->num) != 1)//用来检测错误输入
{
printf("输入有误,请重新输入学号!\n");
getchar();
}
printf("请输入分数:\n");
while(scanf("%d",&p1->score) != 1)//用来检测错误输入
{
printf("输入有误,请重新输入分数!\n");
getchar();
}
}
p2->next = NULL;
return head;
}
void print(struct Student *head)
{
printf("共有%d条记录\n",n);
while(head)
{
printf("学号为:%d\t分数为:%d\n",head->num,head->score);
head =head->next;
}
}
struct Student *insert_link(struct Student *head,int num)
{
struct Student *p1,*p2;
if(head == NULL)//如果链表为空,插入新记录
{
struct Student stu;
head = &stu;
printf("该表为空表,添加记录!\n");
printf("请输入学号:\n");
while(scanf("%d",&stu.num) != 1)//用来检测错误输入
{
printf("输入有误,请重新输入学号!\n");
getchar();
}
printf("请输入分数:\n");
while(scanf("%d",&stu.score) != 1)//用来检测错误输入
{
printf("输入有误,请重新输入分数!\n");
getchar();
}
stu.next = NULL;
p1 = NULL;
p2 = NULL;
return head;
}
else//链表不为空
{
p1 = head;
while(p1->num!=num&&p1->next != NULL)//遍历链表
{
p2 = p1;
p1 = p1->next;
}
if(p2->num == num)//输入学号得到匹配,在此学号之后进行插入
{
struct Student stu;
printf("请输入学号:\n");
while(scanf("%d",&stu.num) != 1)//用来检测错误输入
{
printf("输入有误,请重新输入学号!\n");
getchar();
}
printf("请输入分数:\n");
while(scanf("%d",&stu.score) != 1)//用来检测错误输入
{
printf("输入有误,请重新输入分数!\n");
getchar();
}
p2->next = &stu;
stu.next = p1;
}
else//无匹配学号,在链表结尾插入
{
struct Student stu;
printf("请输入学号:\n");
while(scanf("%d",&stu.num) != 1)//用来检测错误输入
{
printf("输入有误,请重新输入学号!\n");
getchar();
}
printf("请输入分数:\n");
while(scanf("%d",&stu.score) != 1)//用来检测错误输入
{
printf("输入有误,请重新输入分数!\n");
getchar();
}
p1->next = &stu;
stu.next = NULL;
}
}
return head;
}
悲剧了,搞不定了……求大神指导啊{:2_30:} {:7_162:}
链表为空
|
-
链表不为空
|