1.链表
什么是链表
链表是一种数据结构,是一种数据存放的思想
数组特点:元素地址连续
数组的缺点:增加、删除、改、查比较困难,特别是增加的时候,不够灵活
链表的每一项都是一个结构体
#include<stdio.h>
struct Test
{
int data;
struct Test *next;
};
int main()
{
int i;
int arr[] = {1,2,3,4};
for(i<0; i<sizeof(arr)/sizeof(arr[0]); i++){
printf("%d ",arr[i]);
}
putchar('\n');
struct Test t1 = {1,NULL};
struct Test t2 = {2,NULL};
struct Test t3 = {3,NULL};
t1.next = &t2;
t2.next = &t3;
printf("use t1 to print three nums\n");
printf("%d %d %d",t1.data,t1.next->data,t1.next->next->data);
return 0;
}
2.链表的静态添加和遍历
静态添加:
struct Test t1 = {1,NULL};
struct Test t2 = {2,NULL};
struct Test t3 = {3,NULL};
struct Test t4 = {4,NULL};//静态添加只需要再定义一个结构体
t1.next = &t2;
t2.next = &t3;
t3.next = &t4;//链表尾的next为下一个结构体的地址
遍历:
void printLink(struct Test *head)
{
struct Test *point;//定义一个节点来存储头结点
point = head;
while(1){
if(point != NULL)//如果point == NULL说明已经到了链表的尾部
{
printf("%d ",point->data);
point = point ->next;//每打印一次,
}
}
}
3.统计链表节点个数以及链表查找
3.1链表节点个数
int getLinkTotalNodeNum(struct Test *head)
{
int cnt = 0;
while(head != NULL){
cnt++;
head = head ->next;
}
return cnt;
}
3.2链表查找
int searchLink(struct Test *head,int a)
{
while(head != NULL){
if(a == head->data){
return 1;
}
head = head ->next;
}
return 0;
}
4.链表的插入