链表的插入

链表的插入功能实现如下:
查找符合的插入位置:
1. 链表为空,把插入链表当成头节点
2. 查到位置为链表的中间元素
3. 没查到位置,加到链表的末尾
4. 查到位置为链表的头节点

这里插入规则是按学号从小到大插入。

#include <iostream>
#include<stdio.h>
#include<malloc.h>
using namespace std;
struct stu{
    int Inum;
    double Dscore;
    char Cname[30];
    struct stu *Snext;
};
int main()
{
    struct stu *head, *tail, *newstu, *p;
    void List(struct stu *);
    struct stu *Insert(struct stu *,struct stu *);
    head = tail = NULL;
    int Inum;
    printf("请输入要插入的数据(学号 成绩 姓名)如要结束输入,请输入学号为0\n");
    scanf("%d",&Inum);
    while(Inum)
    {
        newstu = (struct stu *)malloc(sizeof(struct stu));
        newstu->Inum = Inum;
        scanf("%lf",&newstu->Dscore);
        scanf("%s",&newstu->Cname);
        head = Insert(head,newstu);
        scanf("%d",&Inum);
    }
    List(head);
    return 0;
}

struct stu *Insert(struct stu *head, struct stu *newstu)
{

    struct stu *p, *last;
    p = head;
    if(p == NULL)//对应第一种情况
    {
        head = newstu;
        head->Snext = NULL;
    }
    else
    {
        while((p != NULL) &&(p->Inum <= newstu->Inum))
        {
            last = p;
            p = p->Snext;
        }
        if(p != NULL)
        {
            if(head == p)//对应第四种情况
            {
                head = newstu;
                newstu->Snext = p;
            }
            else//对应第三种情形
            {
                newstu->Snext = last->Snext;
                last->Snext = p;
            }
        }
        else//对应第二种情形
        {
            last->Snext = newstu;
            newstu->Snext = NULL;
        }
    }
    return head;
}
void List(struct stu *head)
{
    struct stu *p;
    printf("您输入的链表为:\n");
    p = head;
    if(p != NULL)
    {
        while(p != NULL)
        {
            printf("%d\t%lf\t%s\n",p->Inum,p->Dscore,p->Cname);
            p = p->Snext;
        }
    }
    else
    {
        printf("此链表为空");
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值