introducing.h 674 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #pragma once
  2. struct ListNode {
  3. int val;
  4. ListNode* next;
  5. ListNode(int x) : val(x), next(/*NULL*/nullptr) {}
  6. };
  7. class Solution {
  8. public:
  9. ListNode* reverseList1(ListNode* head)
  10. {
  11. if (!head || !head->next)
  12. {
  13. return head;
  14. }
  15. ListNode* prevNode = nullptr, * nextNode = nullptr;
  16. while (head->next)
  17. {
  18. nextNode = head->next;
  19. head->next = prevNode;
  20. prevNode = head;
  21. head = nextNode;
  22. }
  23. head->next = prevNode;
  24. return head;
  25. }
  26. ListNode* reverseList2(ListNode* head)
  27. {
  28. if (!head || !head->next)
  29. {
  30. return head;
  31. }
  32. ListNode* last = reverseList2(head->next);
  33. head->next->next = head;
  34. head->next = nullptr;
  35. return last;
  36. }
  37. };