关于线性表的问题,写代码

建立一个结点值为学生姓名和成绩的长度大于5的链表,在任意位置进行插入、删除结点操作

代码如下:


#include <stdio.h>
#include <stdlib.h>
struct Student
{
    char name[20];
    int score;
};

struct Node 
{
    struct Student stu;
    struct Node* next;
};
//创建链表
struct Node* createList()
{
    int i,n;
    struct Node* head,*p,*t;
    head = (struct Node*)malloc(sizeof(struct Node));
    head->next = NULL;
    p = head;
    printf("请输入学生个数:");
    scanf("%d",&n);
    for (i=0;i<n;i++)
    {
        printf("请输入学生%d的姓名和成绩" , i+1); 
        t = (struct Node*)malloc(sizeof(struct Node));
        scanf("%s %d",t->stu.name , &(t->stu.score));
        t->next = NULL;
        p->next = t;
        p = t;
    }
    return head;
}
//显示链表
void printList(struct Node* head)
{
    struct Node* p;
    if(head == NULL) return;
    p = head->next;
    while(p)
    {
        printf("%s : %d\n",p->stu.name,p->stu.score);
        p = p->next;
    }
}
//获取链表长度(不含头结点)
int getListLength(struct Node* head)
{
    int len = 0;
    struct Node* p;
    if(head == NULL) return len;
    p = head->next;
    while(p)
    {
        len++;
        p = p->next;
    }
    return len;
}
//插入链表
struct Node* insertList(struct Node* head,int pos, struct Student stu)
{
    int len;
    struct Node* p,*t;
    len = getListLength(head);
    if (pos < 1 || pos > len+1)
    {
        printf("插入位置不合适,插入失败\n");
        return head;
    }
    t = (struct Node*)malloc(sizeof(struct Node));
    t->stu = stu;
    t->next = NULL;
    p = head;
    pos--;
    while(pos-- && p )
    {
        p = p->next;
    }
    if (p)
    {
        t->next = p->next;
        p->next = t;
    }
    return head;
}
//删除链表节点
struct Node* deleteList(struct Node* head,int pos)
{
    int len;
    struct Node* p,*t;
    len = getListLength(head);
    if (pos < 1 || pos > len)
    {
        printf("删除位置不合适,删除失败\n");
        //cout << "删除位置不合适,删除失败" <<endl;
        return head;
    }
    //
    p = head;
    pos--;
    while(pos-- && p )
    {
        p = p->next;
    }
    if (p)
    {
        if(p->next)
        {
            t = p->next;
            p->next = t->next;
            free(t);
            t = 0;
        }
    }
    return head;
}


int main()
{
    int pos;
    struct Student stu;
    struct Node* head = createList();
    printf("链表数据为:\n");
    printList(head);
    printf("请输入插入位置:");
    scanf("%d",&pos);
    printf("请输入插入的学生姓名和成绩:" );
    scanf("%s %d",stu.name,&stu.score);
    head = insertList(head,pos,stu);
    printf("插入后链表数据为:\n");
    printList(head);
    printf("请输入需要删除的位置:");
    scanf("%d",&pos);
    head = deleteList(head,pos);
    printf("删除节点后链表的数据:\n");
    printList(head);
    return 0;
}