1. 题目
2. 笔者的解法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
int tmp,carray=0;
struct ListNode * tmpnode,* headnode,* prenode;
headnode=calloc(1,sizeof(struct ListNode));
tmpnode=headnode;
for(;l1 != NULL || l2 != NULL; ){
if( l1==NULL && l2 != NULL)
tmp=l2->val+carray;
else if(l1 !=NULL && l2 == NULL)
tmp=l1->val+carray;
else
tmp=l1->val+l2->val+carray;
tmpnode->val=tmp%10;
carray=tmp/10;
tmpnode->next=calloc(1,sizeof(struct ListNode));
prenode=tmpnode;
tmpnode=tmpnode->next;
if(l1 != NULL)
l1=l1->next;
if(l2 != NULL)
l2=l2->next;
}
if(carray == 1){
tmpnode->val=1;
tmpnode->next=NULL;
}
else{
free(tmpnode);
prenode->next=NULL;
}
return headnode;
}
3. 优质解法
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode p = l1, q = l2, curr = dummyHead;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null) p = p.next;
if (q != null) q = q.next;
}
if (carry > 0) {
curr.next = new ListNode(carry);
}
return dummyHead.next;
}
4. 总结
该题笔者和优质解法的思路一样,本题也不涉及其他算法知识,就是简单的操作链表和两数相加的进位处理。且本题目稍作了简化,将数以倒序方式存入链表。否则又要一些代码来处理正序问题。本题算法时间复杂度,假设最大的数的节点数为 ,则时间复杂度为 。