请选择 进入手机版 | 继续访问电脑版
查看: 370|回复: 0

[云计算] c实现一些基本的数据结构-链表顺序存储结构

725

主题

725

帖子

2188

积分

猿er

Rank: 1

积分
2188
发表于 2016-8-14 17:58:24
c实现一些基本的数据结构
运行环境。Ubuntu gcc
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #define LIST_INIT_SIZE 100
  4. #define INCREMENT_SIZE 10
  5. typedef int DataType;
  6. typedef struct{
  7. DataType *elem;
  8. int length;
  9. int listsize;
  10. }sqlist,*plist;
  11. DataType initList(plist l)
  12. {
  13. l->elem = (DataType *)malloc(sizeof(DataType)*LIST_INIT_SIZE);
  14. if(!l->elem) return 0;
  15. l->length = 0;
  16. l->listsize = LIST_INIT_SIZE;
  17. return 1;
  18. }
  19. DataType insertList(plist l,int i, DataType e)
  20. {
  21. DataType *p;
  22. if(i < 1 || i > l->length+1) return 0;
  23. if(l->length >= l->listsize)
  24. {
  25. l->elem = (DataType *)realloc(l->elem,(LIST_INIT_SIZE+INCREMENT_SIZE)*sizeof(DataType));
  26. }
  27. for(p = l->elem + l->length-1; p >= l->elem + l->length-1; --p) *(p+1) = *p;
  28. *(l->elem+i-1) = e;
  29. l->length++;
  30. return 1;
  31. }
  32. DataType deleteList(plist l,int i, DataType *e)
  33. {
  34. DataType *p;
  35. if(i < 1 || i > l->length) return 0;
  36. *e = *(l->elem+i-1);
  37. for(p = l->elem+i-1;p <= l->elem+l->length; p++) *p = *(p-1);
  38. l->length--;
  39. }
  40. DataType locationList(plist l, DataType e)
  41. {
  42. DataType *p;
  43. int j = 0;
  44. for(p = l->elem;(p <= l->elem+l->length) ;p++)
  45. {
  46. ++j;
  47. if(*p == e)
  48. {
  49. return j;
  50. }
  51. }
  52. return j;
  53. }
  54. DataType mergeList(sqlist la,sqlist lb, plist lc)
  55. {
  56. DataType *pa,*pb,*pc;
  57. pa = la.elem;
  58. pb = lb.elem;
  59. lc->length = la.length + lb.length;
  60. pc = lc->elem = (DataType *) malloc(sizeof(DataType)*(lc->length));
  61. if(!lc->elem) return 0;
  62. while(pa <= la.elem + la.length-1 && pb <= lb.elem+lb.length-1)
  63. {
  64. if(*pa < *pb) *pc++ = *pa++;
  65. else *pc++ = *pb++;
  66. }
  67. while(pa <= la.elem+la.length-1) *pc++ = *pa++;
  68. while(pb <= la.elem+lb.length-1) *pc++ = *pb++;
  69. return 1;
  70. }
  71. void main()
  72. {
  73. sqlist l,la,lc;
  74. int i;
  75. initList(&l);
  76. insertList(&l,1,3);
  77. printf("the length is %d\n",l.length);
  78. printf("\n");
  79. printf("show list :\n");
  80. for(i=0;i<l.length;i++)printf(" the %d number is %d\n",i,l.elem[i]);
  81. initList(&la);
  82. insertList(&la,1,2);
  83. printf("\n");
  84. printf("show list a:\n");
  85. for(i=0;i<la.length;i++)printf(" the %d number is %d\n",i,la.elem[i]);
  86. mergeList(l,la,&lc);
  87. printf("\n");
  88. printf("show list c:\n");
  89. for(i=0;i<lc.length;i++)printf(" the %d number is %d\n",i,lc.elem[i]);
  90. printf("\n");
  91. i = locationList(&l,3);
  92. printf("the location is: %d\n",i);
  93. deleteList(&l,1,&i);
  94. printf("the delete number is %d\n",i);
  95. printf("the length is %d\n",l.length);
  96. }
复制代码



上一篇:冒泡排序
下一篇:顺序表的实现
回复

使用道具 举报