当前位置:   article > 正文

线性表顺序存储结构的表达与实现_顺序存储结构的表达方式

顺序存储结构的表达方式
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #define LIST_INIT_SIZE 10
  4. #define LISTINCREMENT 5
  5. typedef int ElemType;
  6. struct SqList{
  7. ElemType *elem;
  8. int length;
  9. int listsize;
  10. };
  11. //初始化线性表
  12. void InitList_Sq(SqList &L){
  13. L.elem = (ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));
  14. if(!L.elem){
  15. printf("ERROR in InitList_Sq\n");
  16. return;
  17. }
  18. L.length = 0;
  19. L.listsize = LIST_INIT_SIZE;
  20. }
  21. //销毁线性表
  22. void DestoryList(SqList &L){
  23. free(L.elem);
  24. L.length = 0;
  25. }
  26. //清空线性表
  27. void ClearList(SqList &L){
  28. L.length = 0;
  29. }
  30. //判断线性表是否为空
  31. int ListEmpty(SqList L){
  32. return (L.length==0) ? 1 : 0
  33. }
  34. //返回线性表的长度
  35. int ListLength(SqList L){
  36. return L.length;
  37. }
  38. //获取线性表中第i个元素
  39. void GetElem(SqList L, int i, ElemType &e){
  40. if(i<1||i>L.length){
  41. printf("OVERFLOW in GetElem\n");
  42. return;
  43. }
  44. e = L.elem[i-1];
  45. }
  46. //向线性表插入元素
  47. void InsertList_Sq(SqList &L, int i, ElemType e){
  48. if(i<1||i>L.length+1){ //这里应该是i>L.length+1,在编写过程中在这里踩过坑
  49. printf("OVERFLOW in InsertList_Sq\n");
  50. return;
  51. }
  52. if(L.length>=L.listsize){
  53. ElemType *temp;
  54. temp = (ElemType *)realloc(L.elem, (L.listsize+LISTINCREMENT)*sizeof(ElemType));//这个部分也应该留意L.listsize+LISTINCREMENT
  55. if(!temp){
  56. printf("ERROR in InsertList_Sq\n");
  57. return ;
  58. }
  59. L.elem = temp;
  60. L.listsize += LISTINCREMENT;
  61. }
  62. ElemType *ptr, *ptr_last;
  63. ptr = &(L.elem[i-1]);
  64. ptr_last = &(L.elem[L.length-1]);//这里和下面的DeleteList_Sq的部分分别为两种取地址的方式,可以灵活使用
  65. for(ptr_last; ptr_last>=ptr; --ptr_last) *(ptr_last+1) = *(ptr_last);
  66. *ptr = e;
  67. ++L.length;
  68. }
  69. void DeleteList_Sq(SqList &L, int i, ElemType &e){
  70. if(i<1||i>L.length){
  71. printf("OVERFLOW in DeleteList_Sq\n");
  72. return;
  73. }
  74. ElemType *ptr, *ptr_last;
  75. e = L.elem[i-1];
  76. ptr = &(L.elem[i-1]);
  77. ptr_last = L.elem+L.length-1;
  78. for(ptr; ptr<ptr_last; ptr++) *ptr = *(ptr+1);
  79. L.length--;
  80. }
  81. int main(){
  82. SqList list;
  83. int e;
  84. InitList_Sq(list);
  85. for(int i=1; i<=9; i++){
  86. InsertList_Sq(list, i, i);
  87. }
  88. InsertList_Sq(list, 26, 0);
  89. InsertList_Sq(list, 5, -1);
  90. for(int i=0; i<list.length; i++){
  91. printf("%d ", list.elem[i]);
  92. }
  93. printf("\n");
  94. DeleteList_Sq(list, 13, e);
  95. printf("%d\n", e);
  96. for(int i=0; i<list.length; i++){
  97. printf("%d ", list.elem[i]);
  98. }
  99. return 0;
  100. }

参考:严蔚敏《数据结构C语言版》

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/559405
推荐阅读
相关标签
  

闽ICP备14008679号