当前位置:   article > 正文

算法二刷day3

算法二刷day3

203.移除链表元素

  1. class Solution {
  2. public:
  3. ListNode* removeElements(ListNode* head, int val) {
  4. ListNode *dummyHead = new ListNode(0);
  5. dummyHead->next = head;
  6. ListNode *cur = dummyHead;
  7. while (cur->next != nullptr) {
  8. if (cur->next->val == val) {
  9. ListNode *tmp = cur->next;
  10. cur->next = cur->next->next;
  11. delete tmp;
  12. }else {
  13. cur = cur->next;
  14. }
  15. }
  16. return dummyHead->next;
  17. }
  18. };

707.设计链表

  1. class MyLinkedList {
  2. public:
  3. struct LinkedNode {
  4. int val;
  5. LinkedNode* next;
  6. LinkedNode(int val) : val(val), next(nullptr){}
  7. };
  8. MyLinkedList() {
  9. _dummyHead = new LinkedNode(0);
  10. _size = 0;
  11. }
  12. int get(int index) {
  13. if ((_size - 1) < index || index < 0) return -1; //先排除下标无效情况
  14. LinkedNode *cur = _dummyHead->next;
  15. while (index--) {
  16. cur = cur->next;
  17. }
  18. return cur->val;
  19. }
  20. void addAtHead(int val) {
  21. LinkedNode *newNode = new LinkedNode(val);
  22. newNode->next = _dummyHead->next;
  23. _dummyHead->next = newNode;
  24. ++_size;
  25. } // 这里不要忘记size++
  26. void addAtTail(int val) {
  27. LinkedNode *cur = _dummyHead;
  28. while (cur->next != nullptr) {
  29. cur = cur->next;
  30. }
  31. LinkedNode *newNode = new LinkedNode(val);
  32. cur->next = newNode;
  33. ++_size;
  34. }
  35. void addAtIndex(int index, int val) {
  36. if (index > _size) return;
  37. if(index < 0) index = 0;
  38. LinkedNode *cur = _dummyHead;
  39. while (index--) {
  40. cur = cur->next;
  41. }
  42. LinkedNode *newNode = new LinkedNode(val);
  43. newNode->next = cur->next;
  44. cur->next = newNode;
  45. _size++;
  46. }
  47. void deleteAtIndex(int index) {
  48. if (index >= _size || index < 0) {
  49. return;
  50. }
  51. LinkedNode *cur = _dummyHead;
  52. while (index--) {
  53. cur = cur->next;
  54. }
  55. LinkedNode* tmp = cur->next;
  56. cur->next = cur->next->next;
  57. delete tmp;
  58. tmp=nullptr;
  59. _size--;
  60. }
  61. void printLinkedList() {
  62. LinkedNode *cur = _dummyHead;
  63. while (cur->next != nullptr) {
  64. cout << cur->next->val << " ";
  65. cur = cur->next;
  66. }
  67. cout << endl;
  68. }
  69. private:
  70. int _size;
  71. LinkedNode *_dummyHead;
  72. };

206.反转链表

  1. class Solution {
  2. public:
  3. ListNode* reverse(ListNode* pre, ListNode* cur) {
  4. if (cur == nullptr) return pre;
  5. ListNode* tmp = cur->next;
  6. cur->next = pre;
  7. return reverse(cur, tmp);
  8. }
  9. ListNode* reverseList(ListNode* head) {
  10. return reverse(nullptr, head);
  11. }
  12. };
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/214786
推荐阅读
相关标签
  

闽ICP备14008679号