上次我们学到:
#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;
}
今天就学到这儿,关于链表的后续操作,博主会更新滴。