首页 > 代码库 > Leetcode 线性表 数 Add Two Numbers

Leetcode 线性表 数 Add Two Numbers

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie


Add Two Numbers

 Total Accepted: 13127 Total Submissions: 58280

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


题意:给定两个代表数字的链表,每个节点里存放一个digit,数字是逆方向的,将这两个链表相加起来

思路:

1.i, j遍历l1,l2至最长,短的补零
2..设置一个进位变量c, 第i次遍历 l1,l2,c的和除以10进位,mod10留在这一位

3.出循环后还要检查是不是还有进位

复杂度:O(m+n), 空间O(m+n)

相关题目:

 Add Binary

/**
 * 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 *result = NULL, *cur = NULL;
    	int c = 0, s1 = 0, s2 = 0;
    	
    	for(ListNode *i = l1; i != NULL; i = i->next) s1++;
    	for(ListNode *i = l2; i != NULL; i = i->next) s2++;
    
    	for(ListNode *i =l1, *j = l2; i != NULL || j != NULL; ){
    		int val1 = i == NULL ? 0 : i->val;
    		int val2 = j == NULL ? 0 : j->val;
    		int r = (val1 + val2 + c) % 10;
    		c = (val1 + val2 + c) / 10;
    		if(result == NULL) cur = (result = new ListNode(r));
    		else {
    			cur->next = new ListNode(r);
    			cur = cur->next;
    		}
    		//
    		if(i != NULL) i = i->next;
    		if(j != NULL) j = j->next;
    	}
    
    	if(c) cur->next = new ListNode(c);
    	return result;
    }
};