数据结构与算法分析-表
2015-05-31 14:27
471 查看
数据结构与算法分析-表(单链表)
表(list)是常见的数据结构。从数学上来说,表是一个有序的元素集合。在C语言的内存中,表储存为分散的节点(node)。每个节点包含有一个元素,以及一个指向下一个(或者上一个)元素的指针。如下图所示:可以看出表的第一个节点是不存数据的,只存下一节点的地址,表的最后一个节点不存地址,仅仅存数据。所以理论上说5个节点的表只含有4个数据。
表的基本操作有,初始化,栓出,插入和栓出某个节点。
初始化和栓出就是分配节点与栓出所有节点
单链表的插入操作顺序如下图所示,假设要插入的节点为P,首先需要malloc一个节点P,然后将P指向A3的位置,然后断开A2节点并指向P。
单链表的节点删除和插入相反,如下图中,需要删除的节点A3,首先需要找到A3呃前一个节点,也就是A2,接着将断开A3并指向一个临时节点,然后将A2指向A4,最后释放A3。
github代码详见这里点击git clone https://github.com/xiabodan/DataStructure.git
#include <stdlib.h> #include <stdio.h> typedef struct node *list; typedef struct node *position; typedef struct node { int data; position next; }node; list init_list(void); void delete_list(list L); int isempty(list L); void insert_node(position L,int data); void delete_node(list L,position P); position find_last(list L); position find_value(list L,int data); position find_pre(list L,position P ); void print(list L); list init_list(void){ list L = (list)malloc(sizeof(node)); L->next = NULL; return L; } void delete_list(list L){ position P ,next; P = L; do{ next = P->next; free(P); P = next; }while(next != NULL); } int isempty(list L){ return (L->next == NULL); } void insert_node(position P,int data){ position tem ; tem = (position)malloc(sizeof(node)); tem->data = data; tem->next = P->next; P->next = tem; } void delete_node(list L,position P){ position pre ; pre = find_pre( L, P); if(pre != NULL) { pre->next = P->next; free(P); } else { printf("delete_node:p is not in the list!\n"); } } position find_last(list L){ position P; P=L; while(P->next != NULL) { P = P->next; } return P; } position find_value(list L,int data){ position P ; P = L; while(P->next != NULL) { P = P->next; if(P->data == data) return P; } return NULL; } position find_pre(list L,position P ){ position tem ; tem = L; while(tem->next != NULL) { if(tem->next == P) return tem; tem = tem->next; } return NULL; } void print(list L){ position P; if(isempty( L)) { printf("print: L is a null list!\n"); return ; } P = L; while(P->next !=NULL) { P = P->next; printf("print:%p : %d \n",P,P->data); } printf("\n"); } int main(int argc ,char** argv) { int a[6]= {1,2,3,4,5,6}; int i=0; list L; L = init_list(); print(L); printf("insert node\n"); for(i=0;i<6;i++) { insert_node( L,a[i]); } print( L); printf("delete node\n"); position P; P = find_value( L, 5); delete_node( L,P); print( L); printf("find node and insert node\n"); P = find_value( L, 2); insert_node( P,111); print( L); delete_list( L); print( L); }
结果:
相关文章推荐
- 数据结构之---C语言实现矩阵的转置
- 数据结构教程 冒泡算法
- hdu 5249区间第k大(学习了下树状数组的搞法)
- 一个简单的数据结构举例——二叉树及…
- 一个简单的数据结构举例——快排结合…
- 【技术-数据结构与算法分析】一致性哈希算法与Java实现
- CodeForces 140C - New Year Snowmen(数据结构)
- 数据结构面试题总结7——数组:最大连续子段和、最大连续子段积
- COJ 1002 WZJ的数据结构(二)(splay模板)
- 数据结构面试题总结6——数组:求两个数组中满足给定和的两个元素
- 数据结构与算法分析——C语言描述
- 稀疏矩阵的快速转置
- 数据结构面试题总结5——数组:找出数组中唯一一个出现一次的元素
- 数据结构之---C语言实现稀疏矩阵
- 数据结构面试题总结4——数组:求两个有序数组中的共同元素
- 数据结构学习
- 数据结构之 --线性表之--串
- 【整理】数据结构与算法【概念】
- 黑马程序员-数据类型、变量作用域和数据结构的学习笔记
- 算法导论14(数据结构的扩张)