码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode2-Add Two Numbers

时间:2015-01-23 21:26:02      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:

题目

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

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

分析:

  这道题并不难,主要是细节的分析和控制,一个特殊情况就是两个列都遍历完之后,但是进位为1,此时要新建一个尾节点来存储这个数。

参考代码:

/**
 * 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) {
        bool jw=0;
        int num=0;
        int sum=0;
        int count = 0;
        ListNode *result, *pre_node, *cur_node;

        while (l1 != NULL && l2 != NULL)
        {
            sum = l1->val + l2->val + jw;
            num = sum % 10;
            cur_node = (ListNode *)malloc(sizeof(ListNode));
            cur_node->val = num;
            cur_node->next = NULL;
            if (count == 0)
            {
                result = cur_node;
                pre_node = cur_node;
            }
            else
            {
                pre_node->next = cur_node;
                pre_node=pre_node->next;
            }
            l1 = l1->next;
            l2 = l2->next;
            count++;
            jw=sum/10;
        }

        while (l1 != NULL)
        {
            sum = l1->val+jw;
            num = sum % 10;
            l1->val=num;
            cur_node->next = l1;
            cur_node=cur_node->next;
            l1 = l1->next;
            jw=sum/10;
        }
        while (l2 != NULL)
        {
            sum = l2->val+jw;
            num = sum % 10;
            l2->val=num;
            cur_node->next = l2;
            cur_node=cur_node->next;
            l2 = l2->next;
            jw=sum/10;
        }
        if(jw==1)
        {
            ListNode *tail=(ListNode *)malloc(sizeof(ListNode));
            tail->val=jw;
            cur_node->next=tail;
            cur_node=cur_node->next;
        }
        cur_node->next = NULL;
        return result;
    }
};

 

LeetCode2-Add Two Numbers

标签:

原文地址:http://www.cnblogs.com/yanqi0124/p/4244985.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!