当前位置:   article > 正文

c++学习-创建链表_c++创建链表

c++创建链表
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. class MyLinkedList {
  5. public:
  6. struct ListNode {
  7. int val;
  8. ListNode* next;
  9. ListNode(int x) : val(x), next(nullptr) {}
  10. };
  11. MyLinkedList() {
  12. size = 0;
  13. dummyhead = new ListNode(0);
  14. }
  15. int get(int index) {
  16. if (index < 0 || index >= size) {
  17. return -1;
  18. }
  19. ListNode *cur = dummyhead->next;
  20. for (int i = 0; i < index; i++) {
  21. cur = cur->next;
  22. }
  23. return cur->val;
  24. }
  25. void addAtHead(int val) {
  26. addAtIndex(0, val);
  27. }
  28. void addAtTail(int val) {
  29. addAtIndex(size, val);
  30. }
  31. void addAtIndex(int index, int val) {
  32. if (index > size) {
  33. return;
  34. }
  35. index = max(0, index);
  36. size++;
  37. ListNode *pred = dummyhead;
  38. for (int i = 0; i < index; i++) {
  39. pred = pred->next;
  40. }
  41. ListNode *toAdd = new ListNode(val);
  42. toAdd->next = pred->next;
  43. pred->next = toAdd;
  44. }
  45. void deleteAtIndex(int index) {
  46. if (index < 0 || index >= size) {
  47. return;
  48. }
  49. size--;
  50. ListNode *pred = dummyhead;
  51. for (int i = 0; i < index; i++) {
  52. pred = pred->next;
  53. }
  54. ListNode *toDelete = pred->next;
  55. pred->next = pred->next->next;
  56. delete toDelete;
  57. }
  58. private:
  59. int size;
  60. ListNode *dummyhead;
  61. };
  62. int main() {
  63. MyLinkedList linkedList; // 创建链表对象
  64. // 使用 addAtTail 方法添加元素
  65. linkedList.addAtTail(1);
  66. linkedList.addAtTail(2);
  67. linkedList.addAtTail(3);
  68. linkedList.addAtTail(4);
  69. linkedList.addAtTail(5);
  70. linkedList.addAtTail(6);
  71. // 打印链表来检查元素
  72. for (int i = 0; i < 6; i++) {
  73. cout << linkedList.get(i) << ' ';
  74. }
  75. cout <<endl;
  76. // 测试其他功能,例如删除和在头部添加
  77. linkedList.deleteAtIndex(3); // 删除索引3的元素,即数字4
  78. linkedList.addAtHead(0); // 在头部添加0
  79. for (int i = 0; i < 6; i++) {
  80. cout << linkedList.get(i) << ' ';
  81. }
  82. cout <<endl;
  83. return 0;
  84. }

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

闽ICP备14008679号