链表的使用

目录

 结构体定义

创建新节点

头插法

尾插法

中间插入

删除头

删除其它


 结构体定义

struct stu 
{
    char data;
    struct stu *next;
};

创建新节点

步骤:定义一个结构体指针变量(方便在函数之间传递值),给创建的指针分配地址(防止野指针),在见键盘上输入需要的值。

struct stu *creatnewpoint(struct stu *head)
{
    static int i=0;
    struct stu *new;
    while(1)        //创建多个节点
    {
    i++;
    new=(struct stu *)malloc(sizeof(struct stu));    //动态分配变量

    printf("please input %d student data ",i);
    scanf("%d",&new->data);    //输入结构体中其它元素的值
    if(new->data==0)        //创建完毕标志
    {
        return head;
    }
    head=creatlowlink(head,new);        //调用增加函数节点,将新节点插入链表    
    }
}

头插法

struct stu insertheadpoint(struct stu *head,struct stu *new)
{
    if(head==NULL)
    {
        if(head==NULL)
        {
            head=new;    //若头节点指向空,就将头节点赋值给他
        }
        else
        {
            new->next=head;        //将新的节点指向头节点的位置
            head=new;            //将头节点前移,指向新节点,这就完成了新节点的创建
        }

    return head;        //头节点的值一直在变,返回新的地址
    }
}

尾插法

struct stu *creatlowlink(struct stu *head,struct stu *new)
{
    struct stu *p=head;        //从尾巴插入,保证头节点不变

    if(p==NULL)
    {
        head=new;            //当头节点没有指向时,将他指向新节点
        return head;
    }
    while(p->next!=NULL)
    {
        p=p->next;        //找到之后一个结构体中的next指针中存放NULL指针的点
    }
    p->next=new;            //向这一点中存放new地址,让他们形成链表连接
    return head;
}

中间插入

遵循先先将new节点连接,在断开上一个,让他指向new节点

struct stu *p;
new->next=p->next;
p->next=new;

删除头

struct *p=head;
head=head->next;
free(p);        //释放空间

删除其它

p  q两个节点,删除q

p->next=q->next;
free(q);

直接将新数据赋值给原来的元素,与数组相似

sturct stu *P;
p=(struct stu)malloc(sizeof(struct stu));
p->data=1;

用if语句判断结构体中的数值是否满足条件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值