标题 C语言两种方式创建链表(头插法与尾插法)
……不多解释了,都在代码注释里
1.头插法
//头插法创建链表
#include<bits/stdc++.h>
using namespace std;
typedef struct node
{
int data;
struct node *next;
}Node;
int main()
{
Node *head,*p,*q,*t;
head=(Node*)malloc(sizeof(Node));//创建头结点
head->next=NULL;//初始化为空链表
int a,n;//要输入的数以及要创建的结点个数
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a;
p=(Node *)malloc(sizeof(Node));
p->data=a;;
p->next=head->next;//头插法类似于插入排序,将原本头结点指向的内容赋值给要插入的结点的后继指针
head->next=p;//再使得头结点指向要插入的结点
//每一次新插入的结点都在头结点的后面,所以输出顺序和输入顺序是逆序
}
t=head->next;//从首结点处开始遍历
while(t!=NULL)
{
cout<<t->data<<" ";
t=t->next;
}
cout<<endl;
}
运行结果:
2.尾插法
//尾插法创建链表
#include<bits/stdc++.h>
using namespace std;
typedef struct node
{
int data;
struct node *next;
}Node;
int main()
{
Node *head,*p,*q,*t;
head=(Node*)malloc(sizeof(Node));//创建头结点
head->next=NULL;//初始化为空链表
int a,n;//要输入的数以及要创建的结点个数
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a;
//动态申请一个空间用于存放结点
p=(Node*)malloc(sizeof(Node));
p->data=a;;
p->next=NULL;//设置当前结点的下一个结点为空
if(head->next==NULL)
head->next=p;//如果这是第一个创建的结点,则将头结点的后继指针指向当前结点
else
q->next=p;//如果不是,则将上一个结点的后继指针指向当前结点
q=p;//指针q也必须指向当前结点,尾插法的关键
}
t=head->next;//从首节点处开始遍历输出
while(t!=NULL)
{
cout<<t->data<<" ";
t=t->next;
}
cout<<endl;
}
运行结果
以上内容若有错误或需要改进之处,欢迎在评论区提出,共同进步。(▽)