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 -> 8Explanation: 342 + 465 = 807.
题目意思就是给定两个链表,每一个链表中的数都是倒序查入的,需要将其取出按插入之前的顺序相加并将每位再按倒序插入新的链表。
第一种思路很简单:分别取出每个链表中的数字再合并组成一个整数,再将两个整数相加后将每位倒序存入新链表;
第二种思路:因为刚好是倒序插入的,所以可以将两个链表对应从头开始相加,将相加后的个位直接存入新链表,
如果有进位则进位保存继续与两个链表的下一节点继续相加
下面是我的代码,格式有点乱
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { typedef struct ListNode list, *listnode; listnode pt, p1, p2, head, last; int a, b = 0; //b保存进位信息,如果有进位则为1,否则为0 head = (listnode)malloc(sizeof(struct ListNode)); head->next = NULL; last = head; pt = head; p1 = l1; p2 = l2; while(p1 || p2) { if(p1 && p2) { a = p1->val + p2->val + b; b = a/10; pt = (listnode)malloc(sizeof(struct ListNode)); pt->val = (a/10)>0?(a%10):a; pt->next = NULL; last->next = pt; last = pt; p1 = p1->next; p2 = p2->next; } else if(p1 && p2==NULL) { a = p1->val + b; b = a/10; pt = (listnode)malloc(sizeof(struct ListNode)); pt->val = (a/10)>0?(a%10):a; pt->next = NULL; last->next = pt; last = pt; p1 = p1->next; } else { a = p2->val + b; b = a/10; pt = (listnode)malloc(sizeof(struct ListNode)); pt->val = (a/10)>0?(a%10):a; pt->next = NULL; last->next = pt; last = pt; p2 = p2->next; } } if(b>0) { pt = (listnode)malloc(sizeof(struct ListNode)); pt->val = b; pt->next = NULL; last->next = pt; } last = head; head = head->next; free(last); //因为头结点未保存数据,所以要free掉,并将头结点后移一位 return head; }