当前位置:   article > 正文

算法二刷day4

算法二刷day4

24. 两两交换链表中的节点

  1. class Solution {
  2. public:
  3. ListNode* swapPairs(ListNode* head) {
  4. ListNode *dummyHead = new ListNode(0);
  5. dummyHead->next = head;
  6. ListNode *cur = dummyHead;
  7. while (cur->next != nullptr && cur->next->next != nullptr) {
  8. ListNode *tmp = cur->next;
  9. cur->next = cur->next->next;
  10. tmp->next = cur->next->next;
  11. cur->next->next = tmp;
  12. cur = cur->next->next;
  13. }
  14. return dummyHead->next;
  15. }
  16. };

19.删除链表的倒数第N个节点

  1. class Solution {
  2. public:
  3. ListNode* removeNthFromEnd(ListNode* head, int n) {
  4. ListNode *dummyHead = new ListNode(0);
  5. dummyHead->next = head;
  6. ListNode *cur = dummyHead;
  7. int count = 0;
  8. while (cur != nullptr) {
  9. count++;
  10. cur = cur->next;
  11. }
  12. // if (n > count) return nullptr;
  13. int k = count - n - 1;
  14. cur = dummyHead;
  15. while (k--) {
  16. cur = cur->next;
  17. }
  18. ListNode *tmp = cur->next;
  19. cur->next = cur->next->next;
  20. delete tmp;
  21. tmp = nullptr;
  22. return dummyHead->next;
  23. }
  24. };

面试题 02.07. 链表相交

  1. class Solution {
  2. public:
  3. ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
  4. ListNode *curA = headA;
  5. ListNode *curB = headB;
  6. int countA = 0, countB = 0;
  7. while (curA != NULL) {
  8. countA++;
  9. curA = curA->next;
  10. }
  11. while (curB != NULL) {
  12. countB++;
  13. curB = curB->next;
  14. }
  15. int k;
  16. if (countA > countB) {
  17. curA = headB;
  18. curB = headA;
  19. k = countA - countB;
  20. }else {
  21. curA = headA;
  22. curB = headB;
  23. k = countB - countA;
  24. }
  25. while (k--) {
  26. curB = curB->next;
  27. }
  28. while (curB != NULL) {
  29. if (curA == curB) return curA;
  30. else {
  31. curA = curA->next;
  32. curB = curB->next;
  33. }
  34. }
  35. return NULL;
  36. }
  37. };

142.环形链表II

  1. class Solution {
  2. public:
  3. ListNode *detectCycle(ListNode *head) {
  4. ListNode *cur1 = head;
  5. ListNode *cur2 = head;
  6. while (cur2 != NULL && cur2->next != NULL) {
  7. cur1 = cur1->next;
  8. cur2 = cur2->next->next;
  9. if (cur1 == cur2) {
  10. ListNode *index1 = head;
  11. ListNode *index2 = cur1;
  12. while (index1 != index2) {
  13. index1 = index1->next;
  14. index2 = index2->next;
  15. }
  16. return index1;
  17. }
  18. }
  19. return NULL;
  20. }
  21. };
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/243543
推荐阅读
相关标签
  

闽ICP备14008679号