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
又是一道链表操作的题目
//2. Add Two Numbers
public ListNode addTwoNumbers(ListNode l1, ListNode l2)
{
if (l1 == null || l2 == null)
return l1 == null ? l2 : l1;
ListNode head = null;
int mark = l1.val + l2.val > 9 ? 1: 0;// 进位标志
head = new ListNode( (l1.val + l2.val) % 10);
l1 = l1.next;
l2 = l2.next;
ListNode p = head;
while(l1 != null && l2 != null)
{
p.next = new ListNode( (l1.val + l2.val + mark) % 10);
mark = l1.val + l2.val + mark > 9 ? 1 : 0;
p = p.next;
l1 = l1.next;
l2 = l2.next;
}
ListNode temp = l1 == null ? l2 : l1;
if(temp == null && mark == 1)
{
p.next = new ListNode(mark);
return head;
}
while( temp != null)
{
p.next = new ListNode( (temp.val + mark) % 10);
mark = temp.val + mark > 9 ? 1: 0;
p = p.next;
temp = temp.next;
}
if(mark == 1)
{
p.next = new ListNode(mark);
}
return head;
}
2019.3.1
又是做了好几次才做对。需要注意的是最后一位进位的处理
int first = l1->val + l2->val;
ListNode * head = new ListNode(first > 9 ? first - 10 : first);
ListNode * cur = head;
bool jin = first > 9;
l1 = l1->next;
l2 = l2->next;
ListNode * remain = NULL;
if (l1 == NULL)
remain = l2;
while (l1 != NULL)
{
if (l2 != NULL)
{
int jin_count = jin ? 1 : 0;
int count = l1->val + l2->val + jin_count;
if (count > 9)
{
jin = true;
count = count - 10;
}
else
{
jin = false;
}
cur->next = new ListNode(count);
cur = cur->next;
l2 = l2->next;
}
else
{
remain = l1;
break;
}
l1 = l1->next;
remain = l2;
}
// 进位
if (jin)
{
if (remain != NULL)
{
while (remain)
{
int val = 1 + remain->val;
if (val > 9)
{
cur->next = new ListNode(val - 10);
cur = cur->next;
remain = remain->next;
jin = true;
}
else
{
cur->next = new ListNode(val);
cur = cur->next;
remain = remain->next;
jin = false;
}
if (jin == false)
{
break;
}
}
}
else
{
cur->next = new ListNode(1);
cur = cur->next;
jin = false;
}
}
if (jin)
{
cur->next = new ListNode(1);
cur = cur->next;
jin = false;
}
cur->next = remain;
return head;
Runtime: 40 ms, faster than 97.14% of C++ online submissions for Add Two Numbers.
Memory Usage: 19.2 MB, less than 48.57% of C++ online submissions for Add Two Numbers.