您的位置:首页 > 编程语言 > Java开发

2. Add Two Numbers(Leetcode)

2016-07-04 18:18 316 查看
题目

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
解题思路一
两个链表同时遍历,由于低位在前,则遍历的时候就可以相加,并将结果存入新的链表,同时需要一个变量保存进位信息。

实现代码(C语言)

struct ListNode {
int val;
struct ListNode *next;
};

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode *result = (struct ListNode *)malloc(sizeof(struct ListNode));
struct ListNode *endResult = result;
int carry = 0;
while(l1 && l2)
{
struct ListNode *p = (struct ListNode *)malloc(sizeof(struct ListNode));
p->next = NULL;
int temp = l1->val + l2->val + carry;
if(temp >= 10)
{
p->val = temp % 10;
carry = temp / 10;
}
else
{
p->val = temp;
carry = 0;
}
result->next = p;
result = p;
l1 = l1->next;
l2 = l2->next;
}
while(l1 && (carry>0))
{
struct ListNode *p = (struct ListNode *)malloc(sizeof(struct ListNode));
p->next = NULL;
int temp = l1->val + carry;
if(temp >= 10)
{
p->val = temp % 10;
carry = temp / 10;
}
else
{
p->val = temp;
carry = 0;
}
result->next = p;
result = p;
l1 = l1->next;
}
if(l1)
{
result->next = l1;
}

while(l2 && (carry>0))
{
struct ListNode *p = (struct ListNode *)malloc(sizeof(struct ListNode));
p->next = NULL;
int temp = l2->val + carry;
if(temp >= 10)
{
p->val = temp % 10;
carry = temp / 10;
}
else
{
p->val = temp;
carry = 0;
}
result->next = p;
result = p;
l2 = l2->next;
}
if(l2)
{
result->next = l2;
}
if(carry > 0)
{
struct ListNode *p = (struct ListNode *)malloc(sizeof(struct ListNode));
p->next = NULL;
p->val = carry;
result->next = p;
}
return endResult->next;
}

解题思路二

先将链表中数字转换为long型,然后两个long型数字相加,再将long型数字存入链表。

实现代码(Java语言):<相同的测试用例,执行时间比C语言的长,C:20ms,Java:36ms>

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
long num1 = listToLong(l1);
long num2 = listToLong(l2);
long num3 = num1 + num2;
System.out.println(num3);
ListNode result = longToList(num3);
return result;

}

public long listToLong(ListNode list)
{
long result = 0;
long yinzi = 1;
while(list != null)
{
result += list.val * yinzi;
yinzi *= 10;
list = list.next;
}
return result;
}
public ListNode longToList(long num)
{

ListNode result = new ListNode((int)(num%10));
result.next = null;
ListNode endResult = result;
num = num / 10;
while(num != 0)
{
ListNode node = new ListNode((int)(num % 10));
result.next = node;
node.next = null;
result = node;
num = num / 10;
}
return endResult;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode C Java