题目:
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
程序:
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
int len1 = link_size(l1);
int len2 = link_size(l2);
if (len1 == 0 || len2 == 0)
return len1 == 0 ? l2 : l1;
if (len2 > len1)
{
ListNode *t = l1;
l1 = l2;
l2 = t;
}
//cout << len1 << endl;
//ListNode *ret = (ListNode*)malloc(sizeof(ListNode));
ListNode *ret = new ListNode(-1);
ListNode *temp, *r;
r = ret;
//ListNode *ret = l1;
int a = 0, b = 0, c = 0, flag = 0;
//ListNode *temp = (ListNode*)malloc(sizeof(ListNode));
while (l1)
{
a = l1->val;
if (l2)
b = l2->val;
else
b = 0;
if (flag)
c = a + b + 1;
else
c = a + b;
if (c > 9)
flag = 1;
else
flag = 0;
c = c % 10;
temp = new ListNode(c);
//temp->val = c;
r->next = temp;
r = temp;
/*l1->val = c;*/
l1 = l1->next;
if (l2)
l2 = l2->next;//若l1比l2长,则l2到头后不能再继续否则会造成栈溢出
/*if (l1->next == NULL)
temp = l1;*/
}
if (flag)
{
ListNode *p = new ListNode(1);
//p->val = 1;
p->next = NULL;
r->next = p;
r = p;
}
//cout << link_size(l1) << endl;
r->next = NULL;
return ret->next;
//return ret;
}
int link_size(ListNode *l)
{
int size = 0;
while (l)
{
size++;
l = l->next;
}
return size;
}
};
点评:
段错误:您的程序发生段错误,提示程序发生段错误,可能是数组越界,堆栈溢出(比如,递归调用层数太多)
原因是l2到头后还在继续向前,在vs上调试的测试案例是等长,以后需要用更多的测试案例来调试