Leetcode 面试题 02.05. 链表求和
给定两个用链表表示的整数,每个节点包含一个数位。
这些数位是反向存放的,也就是个位排在链表首部。
编写函数对这两个整数求和,并用链表形式返回结果。
示例:
输入:(7 -> 1 -> 6) + (5 -> 9 -> 2),即617 + 295
输出:2 -> 1 -> 9,即912
进阶:假设这些数位是正向存放的,请再做一遍。
示例:
输入:(6 -> 1 -> 7) + (2 -> 9 -> 5),即617 + 295
输出:9 -> 1 -> 2,即912
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-lists-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解决后就通过了:
tmp->next=NULL;//这一行导致了结构体内存问题。
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
int jinwei=0;
int sum = 0;
struct ListNode* p = head;
while(l1 || l2 || jinwei){
sum = 0;
if(l1){
sum = sum + l1->val;
l1 = l1->next;
}
//printf("%d\r\n",sum);
if(l2){
sum = sum + l2->val;
l2 = l2->next;
}
sum = sum + jinwei;
//printf("%d\r\n",sum);
struct ListNode* tmp = (struct ListNode*)malloc(sizeof(struct ListNode));
tmp->val = sum%10;
tmp->next=NULL;//这一行导致了结构体内存问题。
jinwei = (sum>=10)?1:0;
//printf("%d\r\n",jinwei);
p->next = tmp;
p=p->next;
}
return head->next;
}