2019-04-04 20:26:28
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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807
我的代码:
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode *p, *q;
p = (struct ListNode *)malloc(sizeof(struct ListNode));
q = (struct ListNode*)malloc(sizeof(struct ListNode));
p = l1->next;
q = l2->next;
struct ListNode *L3 = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode *m = L3;
int tag = 0;//表示进位
while (q != NULL && p != NULL) {
struct ListNode *n = (struct ListNode*)malloc(sizeof(struct ListNode));
n->val = p->val + q->val+tag;
if (n->val > 9) {
tag = n->val / 10;
n->val = n->val % 10;
n->next = NULL;
m->next = n;
m = m->next;
q = q->next;
p = p->next;
struct ListNode *p1;
p1= (struct ListNode *)malloc(sizeof(struct ListNode));
p1->next = NULL;
p1 = L3->next;
return p1;
在自己的vs里面调试什么的都没有问题,但是一在leetcode的运行环境中就不行了。
Line 70: Char 15: runtime error: member access within misaligned address 0xbebebebebebebebe for type 'struct ListNode', which requires 8 byte alignment (ListNode.c) 0xbebebebebebebebe: note: pointer points here <memory cannot be printed>
弄过了很久也没有弄出来。(果断去参考大佬的了)
int x,y;
int sum=0;
int c=0;
struct ListNode* head;
struct ListNode* ptr;
head=(struct ListNode*)malloc(sizeof(struct ListNode));
x=l1->val;
y=l2->val;
head->val=(x+y)%10;
c=(x+y)/10;
l1=l1->next;
l2=l2->next;
ptr=head;
while(l1 || l2)
x=0;
y=0;
if(l1)
x=l1->val;
l1=l1->next;
if(l2)
y=l2->val;
l2=l2->next;
sum=x+y;
ptr->next=(struct ListNode*)malloc(sizeof(struct ListNode));
ptr=ptr->next;
ptr->val=(sum+c)%10;
c=(sum+c)/10;
if(c)
ptr->next=(struct ListNode*)malloc(sizeof(struct ListNode));
ptr=ptr->next;
ptr->val=c;
ptr->next=NULL;
return head;
ok,good day~