#Leetcode# 445. Add Two Numbers II

https://leetcode.com/problems/add-two-numbers-ii/

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7

代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *num1 = reverseList(l1);
        ListNode *num2 = reverseList(l2);
        
        ListNode *res = new ListNode(-1);
        ListNode *cur = res;
        
        int k = 0;
        while(num1 || num2) {
            int n1 = num1 ? num1 -> val : 0;
            int n2 = num2 ? num2 -> val : 0;
            int sum = n1 + n2 + k;
            k = sum / 10;
            cur -> next = new ListNode(sum % 10);
            cur = cur -> next;
            if(num1) num1 = num1 -> next;
            if(num2) num2 = num2 -> next;
        }
        if(k) cur -> next = new ListNode(1);
        return reverseList(res -> next);
    }
    ListNode* reverseList(ListNode* head) {
        ListNode *revhead = NULL;
        ListNode *pnode = head;
        ListNode *pre = NULL;
         
        while(pnode) {
            if(!pnode -> next)
                revhead = pnode;
             
            ListNode *nxt = pnode -> next;
            pnode -> next = pre;
            pre = pnode;
            pnode = nxt;
        }
        return revhead;
    }
};

  Add Two Numbers 不同的是顺序反过来了 需要反转 刚好下午写过一个反转链表

FHFHFH

猜你喜欢

转载自www.cnblogs.com/zlrrrr/p/10293288.html