1.头插法
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct people
{
int age;
struct people* next;
}link;
int main()
{
link* head = (link*)malloc(sizeof(link));
link* new, * front;
front = head;
int i, n;
scanf("%d", &n);
for (i = 0; i < n; i++)
{
new = (link*)malloc(sizeof(link));
new->age = i;
new->next = NULL;
new->next = front->next;
front->next = new;
}
link* p = head->next;
for (i = 0; i < n; i++)
{
printf("%d ", p->age);
p = p->next;
}
return 0;
}
2.尾插法
#define _CRT_SECURE_NO_WARNINGS 1标签:int,pnew,next,链表,link,new,Link From: https://blog.51cto.com/u_15841666/5904101
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node
{
int data;
struct node* next;
}Link;
int main()
{
Link* head = (Link*)malloc(sizeof(Link));
Link* tail, * pnew;
tail = head;//尾指针指向头指针
int n;
int i;
scanf("%d", &n);
for (i = 0; i < n; i++)
{
pnew = (Link*)malloc(sizeof(Link));//创造新结点
pnew->data = i;//给数据域赋值
pnew->next = NULL;//指针域设为空
tail->next = pnew;//新结点地址赋给尾节点的指针域
tail = pnew;//尾指针指向新结点(新结点也就是最后一个结点)
}
Link* p = head->next;
for (i = 0; i < n; i++)
{
printf("%d ", p->data);
p = p->next;
}
return 0;
}