文章目录
所有代码实现:Tian-hy/c_ds
1. 基本介绍
- 将线性表 L = ( a 0 , a 1 , ⋯ , a n − 1 ) L=(a_0, a_1,\cdots, a_{n-1}) L=(a0,a1,⋯,an−1)中各元素分布在存储器的不同存储块,称为结点,通过地址或指针建立元素之间的联系。
- 每个结点有一个
data
和一个next
指针,data
存储数据元素 a i a_i ai,next
指向下一个结点,最后一个元素的指针指向NULL
2. 基本用法
- 定义:
typedef struct node{
data_t data; //结点的数据域
struct node *next; //结点的后继指针域
}listnode, *linklist;
- 用法:
//在堆空间中声明
linklist p = (linklist)malloc(sizeof(listnode));
p->data = value; //赋值
//在栈空间中声明
linknode a;
a.data = value; //赋值
- 假设
p
指向链表中结点 a i a_i ai,也就是 p → a i ∣ n e x t → a i + 1 ∣ n e x t → ⋯ p\rightarrow a_i|next\rightarrow a_{i+1}|next\rightarrow \cdots p→ai∣next→ai+1∣next→⋯,如果要获取 a i a_i ai,写作p->data
;取 a i + 1 a_{i+1} ai+1,写作p->next->data
;若指针p
的值为NULL
,则它不指向任何结点,此时取地址会爆段错误
3. 单链表实现
3.1 创建结点
linklist create(){
linklist header;
header = (linklist)malloc(sizeof(listnode));
if (header == NULL){
printf("malloc failed\n");
}
header->data = 0;
header->next = NULL;
return header;
}
3.2 在链表尾插入新的结点
int append(linklist header, int value){
if (header == NULL){
printf("Header is NULL");
return -1;
}
// new node
linklist p, cur_node;
if ((p = (linklist)malloc(sizeof(listnode))) == NULL){
printf("malloc failed\n");
return -1;
}
p->data = value;
p->next = NULL;
//locate the tail of the list
cur_node = header;
while (cur_node->next != NULL)