当前位置:   article > 正文

707 设计链表——dummyHead好用

707 设计链表——dummyHead好用

我算是知道dummyHead虚假头节点的妙处了,addAtHead的时候,不用判断链表是否为空,直接把新节点往dummyHead后面一连就可以

注意链表的长度要实时更新!

  1. class MyLinkedList {
  2. private:
  3. ListNode* _dummyHead;
  4. int _size;
  5. public:
  6. //创建一个空链表,把成员变量初始化一下
  7. MyLinkedList() {
  8. _dummyHead = new ListNode(0);
  9. _size = 0;//链表的长度记得要实时更新!
  10. }
  11. int get(int index) {
  12. if((index < 0) || (index >= _size)) return -1;
  13. ListNode* cur = _dummyHead;
  14. //假设索引为3,dum 0 1 2 3,要找4次,cur成为我们要的节点
  15. for(int i = 0; i <= index; i++) {
  16. cur = cur->next;
  17. }
  18. return cur->val;
  19. }
  20. void addAtHead(int val) {
  21. ListNode* newNode = new ListNode(val);
  22. newNode->next = _dummyHead->next;
  23. _dummyHead->next = newNode;
  24. _size++;//增加节点,链表长度更新
  25. }
  26. void addAtTail(int val) {
  27. ListNode* cur = _dummyHead;
  28. while(cur->next != nullptr) {
  29. cur = cur->next;
  30. }
  31. ListNode* newNode = new ListNode(val);
  32. cur->next = newNode;
  33. _size++;
  34. }
  35. void addAtIndex(int index, int val) {
  36. if(index > _size) return;
  37. else if(index == _size) {
  38. addAtTail(val); return;
  39. }
  40. else if(index == 0) {
  41. addAtHead(val); return;
  42. } else {
  43. ListNode* cur = _dummyHead;
  44. while(index--) {
  45. cur = cur->next;
  46. }
  47. ListNode* newNode = new ListNode(val);
  48. newNode->next = cur->next;
  49. cur->next = newNode;
  50. _size++;
  51. }
  52. }
  53. void deleteAtIndex(int index) {
  54. if((index < 0) || (index >= _size)) return;
  55. ListNode* cur = _dummyHead;
  56. while(index--) {
  57. cur = cur->next;
  58. }
  59. ListNode* tem = cur->next;
  60. cur->next = cur->next->next;
  61. delete tem;
  62. _size--;
  63. }
  64. };
  65. /**
  66. * Your MyLinkedList object will be instantiated and called as such:
  67. * MyLinkedList* obj = new MyLinkedList();
  68. * int param_1 = obj->get(index);
  69. * obj->addAtHead(val);
  70. * obj->addAtTail(val);
  71. * obj->addAtIndex(index,val);
  72. * obj->deleteAtIndex(index);
  73. */

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

闽ICP备14008679号