1.链表的定义
链表:由一系列结点组成,每个结点包括两个部分:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域。
//我们用结构体去存储每一个节点
//此处进行结构体的定义并进行重命名
typedef struct Node
{
int data;
struct Node*next;
}Node;
2.创建单链表
创建单链表常见的有头插法和尾插法两种,下面我们进行简单介绍:
(1).头插法
步骤:(假设要加入的新节点的数据域是x)
1.创建头节点head,并且将头结点head指向空(即head=NULL)
2.创建一个新的结点p,使得新结点p的数据域p->data=x,并使当前结点p的下一结点为head(即p->next=head)
3.使head前移,即使head=p
int main()
{
int n,i=0,sum=0;
Node *head=NULL,*p;
scanf("%d",&n);//你所需要创建的节点个数
while(i<n)
{
int x;
scanf("%d",&x);
p=(Node*)malloc(sizeof(Node));//申请一个节点的地址
p->data=x;
p->next=head;
head=p;
i++;
}
}
头插法完整代码:
#include <stdio.h>
#include <malloc.h>
typedef struct Node
{
int data;
struct Node*next;
}Node;
int main()
{
int n,i=0,sum=0;
Node *head=NULL,*p;
scanf("%d",&n);
while(i<n)
{
int x;
scanf("%d",&x);
p=(Node*)malloc(sizeof(Node));
p->data=x;
p->next=head;
head=p;
i++;
}
while(head!=NULL)
{
printf("%d\t",head->data);
head=head->next;
}
return 0;
}
(2).尾插法
步骤:详见代码中注释
#include <stdio.h>
#include <malloc.h>
typedef struct Node
{
int data;
struct Node*next;
}Node;
int main()
{
int n,i;
scanf("%d",&n);
Node *head,*p,*r;//创建头指针head,尾指针r,新增节点p
head=(Node*)malloc(sizeof(Node));//为头指针开辟一块内存
r=(Node*)malloc(sizeof(Node));//为尾指针开辟一块内存
head->next=NULL;
r=head;//最初head与r都指向NULL
for(i=0;i<n;i++)
{
int x;
scanf("%d",&x);
p=(Node*)malloc(sizeof(Node));//为新增节点开辟一块内存
p->data=x;
r->next=p;
r=p;
}
r->next=NULL;//最终使尾节点指向NULL
while(head->next!=NULL)//打印链表
{
printf("%d\t",head->next->data);
head=head->next;
}
return 0;
}
3.打印链表
我们只需要判断当前节点的指针域(或者当前节点的下一节点的指针域)是否为NULL,然后输出即可:
//头插法输出
while(head!=NULL)
{
printf("%d\t",head->data);
head=head->next;
}
//尾插法输出
while(head->next!=NULL)
{
printf("%d\t",head->next->data);
head=head->next;
}
如有问题,欢迎在评论区提问