判空:list_empty(L) 空返回1,非空为0
/* * list_empty : Is list empty? * para L : list * @ret 1--empty 0--not empty -1--failed * */ int list_empty(sqlink L){ if (L == NULL) return -1; if (L->last == -1) return 1; else return 0; }
求表长:length(L)
/* * list_length : return the length of list * para L : list * @ret -1--failed * */ int list_length(sqlink L){ if (L == NULL) return -1; return (L->last + 1); }
插入:Insert(L,x,i)将元素x插入到表L中第i个元素a~i~之前,且表长+1
其中的三个问题:
last < (N - 1)
0 ⩽ p o s ⩽ l a s t + 1 0 \leqslant pos \leqslant last+10⩽pos⩽last+1
如果在last+1插入不需要移动,否则从后往前依次移动。
int list_insert(sqlink L, data_t value, int pos){ int i; if (L == NULL) printf("list is invalid\n"); //full if (L->last == N-1){ printf("list is full\n"); return -1; } //check para pos [0, last+1] if ( pos < 0 || pos > L->last+1){ printf("Pos is invalid\n"); return -1; } //move for (i = L->last; i >= pos; i--){ L->data[i+1] = L->data[i]; } //update last L->data[pos] = value; L->last ++; return 0; }
释放空间:list_free(sqlink L);
int list_free(sqlink L){ if (L == NULL) return -1; free(L); L = NULL; return 0; }
显示所有元素:list_show(sqlink L);
int list_show(sqlink L){ int i; if(L == NULL) return -1; if(L->last == -1) printf("list is empty\n"); for (i = 0; i <= L->last; ++i){ printf("%d ", L->data[i]); } puts(""); return 0; }
显示所有元素:list_delete(sqlink L, int pos);
int list_delete(sqlink L, int pos){ if (L == NULL){ printf("list is invalid\n"); return -1; } if (L->last == -1){ printf("list is empty\n"); return -1; } //pos [0,last] if (pos < 0 || pos > L->last){ printf("delete pos is invalid\n"); return -1; } //move for (int i = pos + 1; i <= L->last; i++){ L->data[i-1] = L->data[i]; } //update L->last --; return 0; }
合并链表:list_merge(sqlink L1, sqlink L2)
int list_merge(sqlink L1, sqlink L2){ int i = 0; while (i <= L2->last){ int ret = list_locate(L1, L2->data[i]); if (ret == -1){ if(list_insert(L1, L2->data[i], L1->last + 1) == -1) return -1; } ++i; } return 0; }
删除线性表中重复的元素:list_purge(sqlink L)
int list_purge(sqlink L){ int i = 1, j; if (L->last == 0) return 0; while ( i <= L->last){ j = i - 1; while ( j >= 0){ if (L->data[i] == L->data[j]){ list_delete(L, i); break; } else{ j--; } } if (j < 0) i++; } return 0; }
线性表的顺序存储优缺点
线性表的顺序存储结构有存储密度高和随机存取的优点
缺点:
要求系统提供一片较大的连续存储空间
插入、删除等运算耗时,且存在元素在存储器中成片移动的现象
写在最后
数据结构开篇之作,今天很多内容需要去gitee仓库里找我练习的代码跟着写来理解,大家加油,接下来的几天时间会继续了解各种数据结构,因为这部分之前我没写完所以更新有点慢,大家和我一起变强呀!最后三连即可提高学习效率!!!
另外我在更新的就是算法笔记的一些例题笔记,这个系列是用于提高我的算法能力,如果有兴趣对算法领域感兴趣找不到合适的入门文章也可以追更,如果我更新的太慢了请大家点赞收藏,一键三连才能更有更新的动力呀0.0