#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<math.h>
#include <stdlib.h>
// 定义一个结构体,一个存放值,一个存放下一个地址
struct listnode
{
int val;
struct listnode * next;
};
//写一个尾插法的函数
//先找到要放在尾巴的链表的null,在定义一个新的链表节点,使新的节点指向null
void inserttail(struct listnode* l, int val) {
//先找尾节点
//尾节点的next是指向null
//定义一个指针 找到尾节点是null,说明就找到了
struct listnode* cur = l;
while (cur->next != NULL) {
cur = cur->next;
}
//此时cur已经指向了尾节点
//先定义一个节点
struct listnode* newnode = (struct listnode*)malloc(sizeof(struct listnode));
newnode->val = val;
newnode->next = NULL; // 新节点的next指向null
//之前找到的null的尾节点,指向新的节点
cur->next = newnode;
}
//写一个遍历列表的函数
void print(struct listnode* l) {
struct listnode* cur = l;
while (cur != NULL) {
printf("%d ", cur->val);
cur = cur->next;
}
}
int main() {
struct listnode* l = (struct listnode*)malloc(sizeof(struct listnode));
l->val = 0;
l->next = NULL;
struct listnode* l1 = (struct listnode*)malloc(sizeof(struct listnode));
l1->val = 10;
l1->next = NULL;
struct listnode* l2 = (struct listnode*)malloc(sizeof(struct listnode));
l2->val = 20;
l2->next = NULL;
//上面的是独立创造的三个节点,后面下面两行代码是使节点连起来。
l->next = l1;
l1->next = l2;
//当前列表是0 10 20
//遍历链表
print(l);
printf("\n");
// 通过尾插法,插入新节点
inserttail(l, 30);
print(l);
return 0;
}
结果演示如下: