方法:翻转就要想到stack

    1. /**
    2. * Definition for singly-linked list.
    3. * struct ListNode {
    4. * int val;
    5. * ListNode *next;
    6. * ListNode() : val(0), next(nullptr) {}
    7. * ListNode(int x) : val(x), next(nullptr) {}
    8. * ListNode(int x, ListNode *next) : val(x), next(next) {}
    9. * };
    10. */
    11. class Solution {
    12. public:
    13. ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    14. stack<int> sl1;
    15. stack<int> sl2;
    16. stack<int> sl3;
    17. ListNode* head=nullptr;
    18. ListNode* temp=nullptr;
    19. int carry=0;
    20. while(l1){
    21. sl1.emplace(l1->val);
    22. l1=l1->next;
    23. }
    24. while(l2){
    25. sl2.emplace(l2->val);
    26. l2=l2->next;
    27. }
    28. while(!sl1.empty()||!sl2.empty()){
    29. int n1=!sl1.empty()?sl1.top():0;
    30. if(!sl1.empty()){
    31. sl1.pop();
    32. }
    33. int n2=!sl2.empty()?sl2.top():0;
    34. if(!sl2.empty()){
    35. sl2.pop();
    36. }
    37. int sum=n1+n2+carry;
    38. sl3.emplace(sum%10);
    39. carry=sum/10;
    40. }
    41. if(carry){
    42. sl3.emplace(carry);
    43. }
    44. while(!sl3.empty()){
    45. int a=sl3.top();
    46. sl3.pop();
    47. if(!head){
    48. head=temp= new ListNode(a);
    49. }else{
    50. temp->next=new ListNode(a);
    51. temp=temp->next;
    52. }
    53. }
    54. return head;
    55. }
    56. };

    上述方法使用了三个栈,可以利用一个临时ListNode指针对数据进行反转

    1. class Solution {
    2. public:
    3. ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
    4. stack<int> s1, s2;
    5. while (l1) {
    6. s1.push(l1 -> val);
    7. l1 = l1 -> next;
    8. }
    9. while (l2) {
    10. s2.push(l2 -> val);
    11. l2 = l2 -> next;
    12. }
    13. int carry = 0;
    14. ListNode* ans = nullptr;
    15. while (!s1.empty() or !s2.empty() or carry != 0) {
    16. int a = s1.empty() ? 0 : s1.top();
    17. int b = s2.empty() ? 0 : s2.top();
    18. if (!s1.empty()) s1.pop();
    19. if (!s2.empty()) s2.pop();
    20. int cur = a + b + carry;
    21. carry = cur / 10;
    22. cur %= 10;
    23. auto curnode = new ListNode(cur);
    24. curnode -> next = ans;
    25. ans = curnode;
    26. }
    27. return ans;
    28. }
    29. };