链表-链表求和 II-中等

描述
假定用一个链表表示两个数,其中每个节点仅包含一个数字。假设这两个数的数字顺序排列,请设计一种方法将两个数相加,并将其结果表现为链表的形式。
您在真实的面试中是否遇到过这个题?  是
样例
给出 6->1->7 + 2->9->5。即,617 + 295。

返回 9->1->2。即,912 。

题目链接

程序


/**
 * Definition of singly-linked-list:
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *        this->val = val;
 *        this->next = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param l1: The first list.
     * @param l2: The second list.
     * @return: the sum list of l1 and l2.
     */
    ListNode *reverseList(ListNode *head){
        ListNode *pre = NULL;
        ListNode *cur = head;
        while(cur){
            ListNode *tmp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
    }
    
    ListNode * addLists2(ListNode * l1, ListNode * l2) {
        // write your code here
        if(l1==NULL || l2==NULL)
            return NULL;
        //将l1和l2链表转化为翻转链表,编程链表求和I问题
        //https://www.lintcode.com/problem/add-two-numbers/description
        l1 = reverseList(l1);
        l2 = reverseList(l2);
        int c = 0;//十位数的数
        int temp = 0;
        ListNode *head = new ListNode(0);
        ListNode *p = head;
        while (l1 != NULL && l2 != NULL)
        {
            temp = l1->val+l2->val + c;
            c = temp/10;//保留十位的数
            temp = temp%10;//节点存个数的数
            p->next = new ListNode(temp);
            p = p->next;
            l1 = l1->next;
            l2 = l2->next;
        }
        while (l1 != NULL)//可能会l1和l2不相等
        {
            temp = l1->val + c;
            c = temp/10;
            temp = temp%10;
            p->next = new ListNode(temp);
            p = p->next;
            l1 = l1->next;
        }
        while (l2 != NULL)//可能会l1和l2不相等
        {
            temp = l2->val + c;
            c = temp/10;
            temp = temp%10;
            p->next = new ListNode(temp);
            p = p->next;
            l2 = l2->next;
        }
        if (c != 0)//最高位进位的情况
        {
            p->next = new ListNode(c);
        }
        //最后再把求和的链表翻转过来
        return reverseList(head->next);
    }
};


猜你喜欢

转载自blog.csdn.net/qq_18124075/article/details/81061495
今日推荐