单链表简单操作一

下面简单的进行单链表的插入删除销毁等操作,想重点的说一下,关于链表插入的时候,分为三种情况,不过原理都一样。在尾插的时候,我们没有遍历链表,不清楚链表的长度,如何判断for循环如何终止呢?

点击(此处)折叠或打开


  1. #include
  2. using namespace std;
  3. struct List {


  4. int data;
  5. struct List *next;
  6. };


  7. List *CreateFirst() {


  8. List *first;
  9. first = new List;
  10. first->next = NULL;
  11. return first;
  12. }


  13. List *InitialList(List *first) { //用尾插法创建链表,并赋值


  14. List *p, *head;
  15. head = first;
  16. /* 首插法创建链表
  17. for (int i = 0; i < 10; i++) {
  18. p = new List;
  19. p->data = i;
  20. p ->next = first ->next;
  21. first ->next = p;

  22. }**/

  23. for (int i = 0; i < 10; i++) {
  24. p = new List;
  25. p->data = i;
  26. head->next = p;
  27. head = p;
  28. head->next = NULL;
  29. }
  30. return first;
  31. }


  32. void PrintList(List *first) {


  33. do {


  34. first = first->next;
  35. cout << first->data << " ";

  36. } while (first != NULL);
  37. }


  38. int PrintLength(List *first) {


  39. int i = 0;
  40. for (List *q = first; q !=NULL ; q = q->next) {


  41. i++;
  42. }
  43. return i-1;
  44. }


  45. int Delete(List *first, int i) {


  46. List *s;
  47. int ddata;
  48. int count = 0;
  49. for (int j = 0; j < i - 1; j++) {


  50. first = first->next;
  51. count++;
  52. }


  53. s = first->next;
  54. ddata = (*s).data;
  55. first->next = s->next;
  56. delete s;
  57. return ddata;
  58. }


  59. void InsertList(List *first, int i, int x) {


  60. /*    List *s; // 插入链表首部
  61. int ddata;
  62. s = new List;
  63. s->data = x;
  64. s->next = first->next;
  65. first->next = s; */


  66. /*    List *s; //插入两结点之间
  67. int ddata;
  68. for (int j = 0; j < i - 1; j++) {


  69. first = first->next;
  70. }
  71. s = new List;
  72. s->data = x;
  73. s->next = first->next;
  74. first->next = s; */


  75. List *s; // 插入链表尾部
  76. int ddata;
  77. for (; first->next != NULL; first = first->next);
  78. s = new List;
  79. s->data = x;
  80. s->next = first->next;
  81. first->next = s;

  82. }


  83. void DestroyList(List *first) {


  84. while (first != NULL) {
  85. List *s;
  86. s = first;
  87. first = first->next;
  88. delete s;
  89. }
  90. }
  91. void main() {


  92. List *s, *t;
  93. s = CreateFirst();
  94. t = InitialList(s);
  95. cout << Delete(t, 3) << endl;
  96. //InsertList(t, 3, 11);
  97. PrintList(t);
  98.  DestroyList(t);

  99. }

由本人水平有限,有错误之处,请大家指正!

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29876893/viewspace-1814392/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/29876893/viewspace-1814392/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值