C语言链表2(创建新的节点以及尾插法)

3 篇文章 0 订阅
2 篇文章 0 订阅

 

上次我们学到:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct Node
{
       int a;
       struct Node*next;
};
struct Node*head = NULL;//全局变量的声明,方便调用
struct Node*end = NULL;

首先是创建一个函数来创建新的节点:

struct Node* creatnewNode()

{

        struct Node*p = (struct Node*)malloc(sizeof(struct Node));

        p->data = 0;

        p->next = NULL;

        return p;

}

接下来是采用尾插法接入节点:分为两种情况,1如果链表为空,则就令头为插入的节点,同时这个插入的节点也为尾巴。

//struct Node* temp = creatnewNode();

if(head == NULL)

{

        head = temp;

        tail = temp;

}

2 若链表不为空,则尾节点的的指针指向要插入的节点,也就是要插入的节点插在尾巴的后面,同时这时这个插入的节点也就变成了尾巴。

tail->next = temp;

tail = temp;

 

 

下面是完整代码(仅能实现尾插法)

#include<stdio.h>
#include<stdlib.h>
struct Node
{
       int data;
       struct node* next;
};
struct Node*head = NULL;
struct Node*tail = NULL;
struct Node* creatnewNode()//创建新节点
{
    struct Node* p=(struct Node*)malloc(sizeof(struct Node));
    p->next=NULL;
    p->data=0;
    return p;
}
void Addnodefromtail(int a)//尾插法
{
       struct Node* temp = creatnewNode();
       temp->data = a;
       if(head == NULL)
       {
              head = temp;
              tail = temp;
       }
       tail->next = temp;
       tail = temp;
}
void printNode()
{
       if(head == NULL)
       {
              printf("error\n");
       }
       struct Node*p = head;
       while(p!=NULL)
       {
              printf("%d ",p->data);
              p = p->next;
       }
}
int main()
{
       int i;
       for(i = 0;i<5;i++)
       {
              Addnodefromtail(i);
       }
       printNode();
       return 0;
}

 

今天就学到这儿,关于链表的后续操作,博主会更新滴。 

 

  • 7
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学编程的土豆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值