两数相加
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
struct ListNode *head = NULL, *last = NULL;
if(!l1)return l2;
if(!l2)return l1;
int con = 0;
int n1 = 0;
int n2 = 0;
if(l1)n1=l1->val;
if(l2)n2=l2->val;
int sum = n1 + n2 + con;
head = last= (struct ListNode *) malloc( sizeof(struct ListNode) );
last->val = sum % 10;
last->next = NULL;
while(l1||l2) {
int n1 = 0;
int n2 = 0;
if(l1)n1=l1->val;
if(l2)n2=l2->val;
int sum = n1 + n2 + con;
last->next = (struct ListNode *)malloc( sizeof(struct ListNode) );
last->next->val = sum % 10;
last = last->next;
last->next = NULL;
con = sum / 10;
if(l1) {
l1 = l1->next;
}
if(l2) {
l2 = l2->next;
}
}
if (con ) {
last->next = (struct ListNode *) malloc( sizeof(struct ListNode) );
last->next->val = 1;
last = last->next;
last->next = NULL;
}
return head->next;
}
方法很早就明确了,但是过程写了好久,有些繁琐,要注意的是,创建一个链表的同时,要注意链表的尾部要时刻指向null。