链表的概念:
链表(Linked List)是数据结构中常见的一种基础数据结构,它由一些列节点(Node)组成,每一个节点都包含两部分,一部分是存储数据的数据域(Data),另一部分是记录下一个节点位置的指针域(Next)。链表中的节点在内存中存储的位置是不连续的,而是通过指针来相互连接。
链表有单向链表和双向链表两种形式。接下来我将通过C语言来实现单链表和双链表的一些基本操作,代码统一使用全局变量的头指针的形式来实现。
单链表:
1、建立单链表:
单链表的建立通常使用头插法或者尾插法;
通用代码:
struct Node { //结构体定义
int data;
struct Node* next;
};
int count = 0; //计算节点的数量
struct Node* head = NULL; //头指针
struct Node* new(int x)
{
struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); //给新节点分配内存
temp->data = x; //赋值
temp->next = NULL;
return temp;
}
头插法将新节点插入链表的开头;
代码实现:
void headList(int data)
{
struct Node* A = new(data); //创建新节点
A->next = head; //新节点的指针指向头指针指向的节点
head = A; //头指针指向新节点
count++;
}
尾插法将新节点插入链表的尾巴;
代码实现:
void lastList(int data)
{
struct Node* k = head; //该变量用来替代头指针来进行移动
struct Node* temp = new(data);
if (k == NULL) //链表为空
{
temp->next = head;
head = temp;
return;
}
while (k->next != NULL) Move to the last node
k = k->next;
temp->next = k->next;
k->next = temp;
count++;
}
2、单链表的按位插入
单链表的按位插入是指在指定位置插入一个节点。具体步骤如下:
- 定义要插入的节点,并赋值。
- 找到要插入位置前一个节点,并定义一个指向该节点的指针p。
- 将要插入节点的next指针指向p的next指针所指向的节点。
- 将p的next指针指向要插入的节点。
代码实现:
void insert(int x, int data) //x是插入位置 data是新节点的数据
{
struct Node* sert = head; //因为head是全局变量
struct Node* temp = new(data);
if (x<1 || x>count) //插入位置非法
{
printf("error!");
return;
}
for (int i = 1; i < x - 1; i++) //移动到插入的位置
sert = sert->next;
temp->next = sert->next;
sert->next = temp;
}
3、单链表的按位查找和按值查找
步骤基本与按位插入一致;
代码实现:
//按位查找
void finder1(int x)
{
struct Node* find = head;
if (head == NULL) //链表为空
{
printf("empty!\n");
return;
}
if (x<1 || x > count) //查找位置非法
{
printf("error!\n");
return;
}
for (i