链表的题,求c语言的代码
整理成绩 plus
小李老师对上次你给的程序功能不太满意,现在他想要你使用链表写一个程
序帮他录入成绩。
要求:使用链表录入学生成绩,并且在任意位置插入新的学生成绩或删除任
意位置成绩(插入命令输入格式“add 位置 i 名字 成绩”,删除命令输入格式
“del 位置 i”
例如:
输入:
3
小杨 94
小周 92
小王 92
输入:add 0 小吴 74
输出:
小吴 74
小杨 94
小周 92
小王 92
输入:del 1
输出:
小吴 74
小周 92
小王 92
#include <stdio.h>
#include <string.h>
typedef struct _stuNode
{
char name[20];
int score;
struct _stuNode * next;
}stuNode,*stulist;
void createStu(stulist L)
{
stulist q = L;
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
stulist p = (stulist)malloc(sizeof(stuNode));
scanf("%s%d",p->name,&p->score);
p->next = NULL;
q->next = p;
q = p;
}
}
void addStu(stulist L,int pos,char *name,int score)
{
stulist q = L;
while(pos-- > 0 && q->next != NULL)
q = q->next;
stulist p = (stulist)malloc(sizeof(stuNode));
strcpy(p->name,name);
p->score = score;
p->next = NULL;
if(q->next == NULL)
q->next = p;
else
{
p->next = q->next;
q->next = p;
}
}
void delStu(stulist L,int pos)
{
stulist q = L;
while(pos-- > 0 && q->next != NULL)
q = q->next;
if(q->next == NULL)
return;
else
{
stulist p = q->next;
q->next = q->next->next;
free(p);
}
}
void printStu(stulist L)
{
stulist p = L->next;
while(p != NULL)
{
printf("%s %d\n",p->name,p->score);
p = p->next;
}
}
int main()
{
stulist L = (stulist)malloc(sizeof(stuNode));
L->next = NULL;
createStu(L);
printStu(L);
char opr[20],name[20];
int score,pos;
scanf("%s%d%s%d",opr,&pos,name,&score);
if(strcmp(opr,"add") == 0)
addStu(L,pos,name,score);
printStu(L);
scanf("%s%d",opr,&pos);
if(strcmp(opr,"del") == 0)
delStu(L,pos);
printStu(L);
return 0;
}