网站建设与管理是哪个软件,免费建设个人手机网站,苏州街网站建设,旅游景区网站建设方案文档✅作者#xff1a;简单^不简单 #x1f525;系列专栏#xff1a;C语言数据结构 #x1f496;如果文章有错误#xff0c;时刻欢迎大家的指正。当然觉得博主的文章还不错的话#xff0c;请点赞#x1f44d;收藏⭐️留言#x1f4dd; #x1f4ac;格言#xff1a;希望我… ✅作者简单^不简单 系列专栏C语言数据结构 如果文章有错误时刻欢迎大家的指正。当然觉得博主的文章还不错的话请点赞收藏⭐️留言 格言希望我们都能朝着光走 目录 相关知识点 1.线性表 2.顺序表 3.链表 相关操作 1.定义数据结构 2.插入 2.1头插法 2.2尾插法 3.删除 完整代码 相关知识点
1.线性表 定义线性表 linear list 是 数据结构 的一种一个线性表是n个具有相同特性的数据元素的有限序列。特点 1.有限的序列 2.序列中的每一个元素都有唯一的前驱和后继 2.顺序表 分配一块连续的内存去存放这些元素例如编程语言中的素组。
3.链表 内存是不连续的元素会各自被分配一块内存内存和内存之间用指针进行相连。 本文重点对单链表的相关操作进行讲解
相关操作
1.定义数据结构
typedef struct Node{int data;struct Node* next;
}Node;2.插入
2.1头插法 将头指针指向的节点赋值给新结点中next指向的节点再将头结点的next从新指向node
//头插法
void headInsert(Node* list,int data){Node* node (Node*)malloc(sizeof(Node));node-data data;node-next list-next;list-next node;list-data;
}2.2尾插法 创建一个新结点将值传入其中再将新结点的next—NULL,最后通过遍历找到以前的尾元素将尾元素的next指向该元素。
//尾插法
void tailInsert(Node* list,int data){Node* head list;Node* node (Node*)malloc(sizeof(Node));node-data data;node-next NULL;list list-next;while(list-next){list list-next;}list-next node;head-data;
}3.删除 删除指定节点时要注意指针指向的节点是否为空之后便是进行扫描与交换数据域再之后就是进行断开释放空间等操作
void delete(Node* list,int data){Node* pre list;Node* current list-next;while(current){if(current-datadata){pre-next current-next;free(current);break;}pre current;current current-next;}list-data--;
}
完整代码
#includestdio.h
#includestdlib.h//开辟空间的头文件//定义数据结构
typedef struct Node{int data;struct Node* next;
}Node;//初始化头节点
Node* initList(){Node* list (Node*)malloc(sizeof(Node));list-data 0;list-next NULL;return list;}//头插法
void headInsert(Node* list,int data){Node* node (Node*)malloc(sizeof(Node));node-data data;node-next list-next;list-next node;list-data;
}//尾插法
void tailInsert(Node* list,int data){Node* head list;Node* node (Node*)malloc(sizeof(Node));node-data data;node-next NULL;list list-next;while(list-next){list list-next;}list-next node;head-data;
}//删除操作
void delete(Node* list,int data){Node* pre list;Node* current list-next;while(current){if(current-datadata){pre-next current-next;free(current);break;}pre current;current current-next;}list-data--;
}//遍历操作
void printList(Node* list){list list-next;while(list){printf(%d,list-data);list list-next;}printf(\n);
}int main(){Node* list initList();headInsert(list,1);headInsert(list,2);headInsert(list,3);headInsert(list,4);headInsert(list,5);tailInsert(list,6);tailInsert(list,7);tailInsert(list,8);tailInsert(list,9);tailInsert(list,10);delete(list,5);delete(list,10);delete(list,3);printList(list);return 0;}