#include<stdio.h>
#include<stdlib.h>
struct node
{
int num;
int score;
struct node *next;
};
//创建
/*
struct node *creat(struct node *head, int n)
{
struct node *p, *q;
int i;
for(i = 1; i <= n; i++)
{
q = (struct node *)malloc(sizeof(struct node));
printf("请输入学号和成绩:\n");
scanf("%d%d",&q->num,&q->score);
q->next = NULL;
if(head == NULL)
{
head = q;
}
else
{
p->next = q;
}
p = q;
}
return head;
}
*/
struct node *creat(struct node *head)
{
struct node *p1,*p2;
//申请结点空间
p1 = (struct node *)malloc(sizeof(struct node));
printf("请输入学号和成绩(当输入的学号和成绩均为0时,停止输入!):\n");
scanf("%d%d",&p1->num,&p1->score);
while(p1->num != 0 && p1->score !=0)
{
p1->next = NULL;//将新结点的指针置为空
if(head == NULL)
{
head = p1;//空表,接入表头
}
else
{
p2->next = p1;//非空表,接到表尾
}
p2 = p1; //为下一次p1开辟空间保留上一次的结点地址
p1 = (struct node *)malloc(sizeof(struct node));//申请下一个新结点空间
scanf("%d%d",&p1->num,&p1->score);
}
return head;
}
//插入函数(按学号)
struct node *insert(struct node *head)
{
//....
struct node *p, *q, *t;
struct node *m;
t = (struct node *)malloc(sizeof(struct node));
printf("请输入学号、成绩:");
scanf("%d%d",&t->num, &t->score);
if(head == NULL) //在空表中插入
{
t->next = NULL;
head = t;
return head;
}
if(head->num > t->num) //插入在表头之前
{
t->next = head;
head = t;
return head;
}
//插在链表中间或末尾
p = head;
q = head->next;
//在链表中查找插入的位置
while(q != NULL && q->num < t->num)
{
p = q;
q = q->next;
}
//如果学号相同,成绩高的在前(晕!实际中是不可能有相同学号的,不过这里只是玩玩...)
if(q->num == t->num)
{
m = q->next;
if(q->score > t->score)
{
q->next = t;
t->next = m;
}
else
{
t->next = q;
p->next = t;
}
}
else
{
t->next = q;
p->next = t;
}
return head;
}
//查询函数
void find(struct node *head)
{
int n;
struct node *p4;
p4 = head;
printf("请输入要查询的学生学号 = ");
scanf("%d",&n);
while(p4 != NULL && p4->num != n)
{
p4 = p4->next;
}
if(p4)
{
puts("---学生的学号\t姓名---");
printf("%d\t%d\n",p4->num,p4->score);
}
else
{
printf("查无此数!");
}
}
/*删除
算法:
从标头结点开始,确定要删除结点的地址p,以及p的前一个结点地址q;
如果p为头结点,删除后应该修改表头指针head,否则修改q结点的指针域;
回收p结点的空间。
*/
struct node *dele(struct node *head)
{
int n;
struct node *p,*q;
p = head;
printf("请输入要删除学生的学号:");
scanf("%d",&n);
while(p != NULL && p->num != n) //查找被删除结点
{
q = p;
p = p->next;
}
if(p == NULL)
{
printf("%d is not found!",n);
}
else if(p == head) //删除表头结点
{
head = p->next;
}
else
{
q->next = p->next; //删除中间结点
}
free(p);
return head;
}
//输出函数
void print(struct node *head)
{
struct node *p3 = head;
if(head != NULL)
while(p3 != NULL)
{
printf("%d\t%d\n",p3->num,p3->score);
p3 = p3->next;
}
}
//测试
void main()
{
struct node *head = NULL;//建立一个空表
// head = creat(head,3);
head = creat(head);
print(head);
// find(head);
// dele(head);
insert(head);
print(head);
}
链表的综合练习:增、删、改、查
最新推荐文章于 2023-05-23 19:37:22 发布