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

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

688

主题

688

帖子

2083

积分

猿er

Rank: 1

积分
2083
发表于 2016-8-14 17:58:24
链表的c实现
运行环境。Ubuntu gcc
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. typedef int Datatype;
  4. typedef struct LNode{
  5. Datatype data;
  6. struct LNode *next;
  7. }LNode,*LinkList;
  8. //insert
  9. Datatype insertList(LinkList l, int i ,Datatype e)
  10. {
  11. LinkList p,s;
  12. p = l;
  13. for(;(i > 1)&& p;i--)
  14. {
  15. p = p->next;
  16. }
  17. if(!p) return 0;
  18. s = (LinkList)malloc(sizeof(LNode));
  19. s->data = e;
  20. s->next = p->next;
  21. p->next = s;
  22. return 1;
  23. }
  24. //delete
  25. Datatype deleteList(LinkList l, int i ,Datatype *e)
  26. {
  27. LinkList p,q;
  28. p = l;
  29. for(;i>1 && (p=p->next);i--);
  30. if(!p) return 0;
  31. q = p->next;
  32. p->next = q->next;
  33. *e = q->data;
  34. free(q);
  35. return 1;
  36. }
  37. //location
  38. Datatype getElement(LinkList l,int i, Datatype *e)
  39. {
  40. LinkList p;
  41. p = l;
  42. while((i >= 1) && p)
  43. {
  44. p = p->next;
  45. --i;
  46. }
  47. *e = p->data;
  48. return 1;
  49. }
  50. void merge_list(LinkList la,LinkList lb, LinkList lc)
  51. {
  52. LinkList pa,pb,pc;
  53. pa = la->next;
  54. pb = lb->next;
  55. lc = pc = la;
  56. while(pa && pb)
  57. {
  58. if(pa->data <= pb->data)
  59. {
  60. pc->next = pa;pc = pa; pa = pa->next;
  61. }
  62. else
  63. {
  64. pc->next = pb;pc = pb; pb = pb->next;
  65. }
  66. }
  67. pc->next = pa?pa:pb;
  68. free(lb);
  69. }
  70. int main()
  71. {
  72. LinkList l,e,la,lc;
  73. l = (LinkList)malloc(sizeof(LNode));
  74. la = (LinkList)malloc(sizeof(LNode));
  75. lc = (LinkList)malloc(sizeof(LNode));
  76. Datatype s=11111;
  77. insertList(l,1,3);
  78. insertList(l,2,4);
  79. insertList(l,3,5);
  80. insertList(la,1,6);
  81. insertList(la,2,7);
  82. insertList(la,3,8);
  83. e =l;
  84. while(e)
  85. {
  86. printf("\nthe insert data is %d",e->data);
  87. e = e->next;
  88. }
  89. printf("\n");
  90. merge_list(l,la,lc);
  91. e = lc;
  92. while(e)
  93. {
  94. printf("\nthe insert data is %d",e->data);
  95. e = e->next;
  96. }
  97. deleteList(l,1,&s);
  98. e =l;
  99. while(e)
  100. {
  101. printf("\nthe insert data is %d",e->data);
  102. e = e->next;
  103. }
  104. getElement(l,2,&s);
  105. printf("\nlocation is %d\n",s);
  106. return 0;
  107. }
复制代码



上一篇:顺序表的实现
下一篇:整除问题
回复

使用道具 举报