單連結串列簡單操作一

Diy_os發表於2015-10-15
下面簡單的進行單連結串列的插入刪除銷燬等操作,想重點的說一下,關於連結串列插入的時候,分為三種情況,不過原理都一樣。在尾插的時候,我們沒有遍歷連結串列,不清楚連結串列的長度,如何判斷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/,如需轉載,請註明出處,否則將追究法律責任。

相關文章