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

C语言链表2(创建新的节点以及尾插法)_第1张图片

 

上次我们学到:

#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;

 C语言链表2(创建新的节点以及尾插法)_第2张图片

 

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

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

 C语言链表2(创建新的节点以及尾插法)_第3张图片

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

 

你可能感兴趣的:(C语言,链表,调用函数,c语言,链表,开发语言)