1.什么是链表?
链表是一种常见的数据结构,链表是由多个结点(自引用结构体)串成的表。
什么是自引用结构体?
自引用结构体是一种特殊的结构体类型,它有一个指针类型的成员,这个指针成员指向与这个结构体一样的类型。
链表就是由一个一个结点(自引用结构体),结点被指针串起组成的表。
链表的头指针,头节点
链表中指向第一个结点的指针,一般新建一个头节点用于存放头指针,头节点可有可无,但是头指针必须要有。只有通过头指针我们才能找到链表,遍历链表中的每一个结点。
2.创建链表步骤分解
1.结构体声明
struct node
{
//存放数据
int data;
//指向下一个结构体的指针
struct data *next;
};
2.结点指针声明
//为了简写,习惯上使用typedef 来将struct node 定义成一个词Node来代替。
typedef struct node Node;
//生成三个结点指针
//head头指针,previou指向最后结点的前一个结点,current指向当前结点(最后一个结点)
Node *head, *previous, *current;
//用于判断头指针是否为空
head = NULL;
一、插入第一个结点
1.生成一个结点由指针current指向该结点
current = (Node *)malloc(sizeof(Node));
2.将该结点的next指向NULL
current->next = NULL:
3.为该结点输入数据
printf("请输入一个数字\n");
scanf("%d",¤t->data);
4.把current赋值给previous,使previous成为要插入的下一个结点的先前结点。
previous = current;
二、插入下一个结点
1.生成第一个结点,由指针current指向该结点
current = (Node *)malloc(sizeof(Node));
2.将current 指向NULL
current->next = NULL;
3.把指针previous的next 从NULL变成current
previous->next = current;
4.为该结点输入数据
printf("请输入一个数字\n");
scanf("%d",¤t->data);
5.把current赋值给previous
previous = current
三、插入下一个结点
插入下一个结点与插入第二个结点类似。
3.创建链表图解
4.整体代码,包括创建单向链表和遍历单向链表
#include<stdio.h>
#include<stdlib.h>
//定义自引用结构体(结点)
struct node
{
int data;
struct node *next;
};
//typedef简写struct node
typedef struct node Node;
//创建链表和遍历链表函数的声明
Node *CreatList();
void DispList(Node *head);
/**
* main函数用于测试
*/
int main(int argc, char const *argv[])
{
Node *head = CreatList();
DispList(head);
return 0;
}
/**
* 遍历链表输出数据
* @Node *head 需要遍历的链表的头指针
*/
void DispList(Node *head)
{
Node *p = head;
printf("链表中的数据如下:\n");
while(p != NULL)
{
printf("%d\n",p->data);
p = p->next;
}
}
/**
* 创建链表
* @return Node* 返回链表的头指针,用户遍历链表。
*/
Node *CreatList()
{
//指向结点的指针变量
Node *head, *previous, *current;
int length;
head = NULL;
//得到链表长度,根据链表长度创建结点
printf("请输入结点个数\n");
scanf("%d",&length);
//创建结点的循环
for(int i = 0; i < length; i++)
{
current = (Node *)malloc(sizeof(Node));
current->next = NULL;
//判断头指针是否为空,如果为空则正在处理第一个结点
if(head == NULL)
{
head = current;
}
else
{
previous->next = current;
}
printf("请输入一个数字\n");
scanf("%d",¤t->data);
previous = current;
}
//返回头指针用于遍历链表
return head;
}