一、单向链表的基本操作
单向链表也需要实现“增、删、改、查”的动作,核心点在于能够熟练掌握在不同的结构体定义下,基本方法的实现。除此之外,还需要掌握的是链表的翻转、链表的串接。其中,链表的删除、翻转和串接容易忘记。
/* create/insert/delete/visit */
#include "stdlib.h"
#include "stdio.h"
typedef struct list_node* list_pointer; //自引用结构
typedef struct list_node{
int data;
list_pointer link;
};
// 建立了一个空的链表
list_pointer ptr = NULL;
list_pointer create2()
{
list_pointer first, second;
first = (list_pointer)malloc(sizeof(struct list_node));
second = (list_pointer)malloc(sizeof(struct list_node));
second->link = NULL;
second->data = 20;
first -> link = second;
first -> data = 10;
return first;
}
void insert(list_pointer *ptr, list_pointer node)
{
list_pointer temp = (list_pointer)malloc(sizeof(struct list_node));
temp->data = 50;
// 插入链表中
if (*ptr) {
temp->link = node->link;
node->link = temp;
} else {
temp->link = NULL;
*ptr = temp;
}
}
// 这里的传参也相当于一个临时变量,不会修改原有链表的指向位置
void visit(list_pointer ptr)
{
for (; ptr; ptr = ptr->link) {
printf("%d ", ptr->data);
}
printf("\n");
}
void main()
{
list_pointer ptr = create2();
insert(&ptr, ptr);
insert(&ptr, ptr->link->link);
insert(&ptr, ptr);
visit(ptr);
}
二、循环链表的基本操作
能够熟练写出循环链表的创建、插入、长度计算、循环链表的清除动作。