栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

 

上次我们学到:

#include
#include
#include
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
#include
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("errorn");
       }
       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;
}

 

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

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/920267.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号