当前位置:   article > 正文

手撕链表~~_js手撕链表

js手撕链表
  1. 链表的创建以及实现增删改查功能,利用了哑节点把头节点“大众化”
  2. //创建结构体
  3. struct Node {
  4. int val;
  5. Node* next;
  6. Node(int val) {
  7. this->val = val;
  8. this->next = nullptr;
  9. }
  10. };
  11. //全局变量
  12. Node* head;
  13. Node* tail;
  14. Node* dummyhead;
  15. //用数组传参创建链表
  16. Node* createList(vector<int>&a) {
  17. for (int i = 0; i < a.size(); i++) {
  18. Node *newnode = new Node(a[i]);
  19. if (!head) {
  20. head = newnode;
  21. tail = newnode;
  22. }
  23. else {
  24. tail->next = newnode;
  25. tail = newnode;
  26. }
  27. }
  28. return head;
  29. }
  30. //打印
  31. void print(Node* head) {
  32. while (head) {
  33. cout << head->val<<" ";
  34. head = head->next;
  35. }
  36. printf("\n");
  37. return;
  38. }
  39. //增加:在index个节点前加节点val(index从0计数)
  40. Node* add(int val,int index) {
  41. if (!head) return head;
  42. dummyhead = new Node(-1);
  43. Node* newnode = new Node(val);
  44. dummyhead->next = head;
  45. Node* cur = dummyhead;
  46. while (index) {
  47. cur = cur->next;
  48. index--;
  49. }
  50. newnode->next = cur->next;
  51. cur->next = newnode;
  52. return dummyhead->next;
  53. }
  54. //删除值为val的所有节点
  55. Node* deleteNode(int val) {
  56. if (!head) return head;
  57. dummyhead = new Node(-1);
  58. dummyhead->next = head;
  59. Node* cur = dummyhead;
  60. while (cur->next) {
  61. if (cur->next->val==val) {
  62. cur->next = cur->next->next;
  63. }
  64. else {
  65. cur = cur->next;
  66. }
  67. }
  68. return dummyhead->next;
  69. }
  70. //改:将节点nums1改为nums2
  71. Node* changeNode(int nums1, int nums2) {
  72. if (!head) return head;
  73. Node* p = head;
  74. while (p) {
  75. if (p->val == nums1) {
  76. p->val = nums2;
  77. }
  78. p = p->next;
  79. }
  80. return head;
  81. }
  82. //查找
  83. bool get(int target) {
  84. if (!head) return head;
  85. dummyhead = new Node(-1);
  86. dummyhead->next = head;
  87. while (head) {
  88. if (head->val == target) {
  89. return 1;
  90. }
  91. head = head->next;
  92. }
  93. return 0;
  94. }

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

闽ICP备14008679号