Leetcode# 2. Add Two Numbers(链表模拟大数算法)
Add Two Numbers(链表)You are given two non-empty linked lists representing two non-negative integers. 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. You may assume the two numbers do not contain any leading zero,except the number 0 itself. Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 题意给定两个非空的链表,表示两个非负整数。数字以相反的顺序存储,每一个节点包含一个数字。将两个数相加并将结果作为链表返回。 2 4 3 5 6 4 ————— 7 0 8 特别像字符串求大数算法,这里题目已经把字符串翻转,简单了不少。 解决方法一:C++版思路很简单,麻烦之处在于指针的使用。sum指向头结点,temp代表移动的指针,在末尾添加元素的操作为: /** * 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) {
int carry = 0;//进位
ListNode *sum = NULL,*temp = NULL;
while(l1 != NULL || l2 != NULL || carry != 0)
{
int now = 0;//当前位数
if(l1!=NULL)
{
now += l1 -> val;
l1 = l1 -> next;
}
if(l2!=NULL)
{
now += l2 -> val;
l2 = l2 -> next;
}
if(carry != 0)
now += carry;
carry = now / 10;
now = now % 10;
//将int型的now转换为ListNode注意看上面的构造函数要传参数的
ListNode *p = new ListNode(now);
//头指针指向temp
if(sum == NULL)
{
temp = p;
sum = temp;
}
else
{
temp -> next = p;
temp = temp -> next;
}
}
return sum;
}
};
解决方法二:Python版解法思路同上。 # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self,x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self,l1,l2):
""" :type l1: ListNode :type l2: ListNode :rtype: ListNode """
sum = None
temp = None
carry = 0
while l1 != None or l2 != None or carry != 0:
now = 0
if l1 != None:
now = now + l1.val
l1 = l1.next
if l2 != None:
now = now + l2.val
l2 = l2.next
if carry != 0:
now = now + carry
carry = now / 10
now = now % 10
q = ListNode(now)
if sum == None:
temp = q
sum = temp
else:
temp.next = q
temp = temp.next
return sum
总结这两种语言思路是一样的,如果不太懂大数算法的可以在这里学习一下:http://www.voidcn.com/article/p-bgqfrziw-ke.html 本地github代码:https://github.com/xuna123/LeetCode/blob/master/Leetcode%23%202.%20Add%20Two%20Numbers.md (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |