2 Add Two Numbers
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
題用是用鏈結串列去存數字,做加法,跟之前1.3用陣列存整數的概念一樣,只是換成了linked list. 要注意是這題目l1跟l2的長度是可以不一樣的,可以l1是0 , l2是1,1或是相反的情況,我本來是想用l1來存結果就好,但是長度可以不一樣的情況下,這樣就變更麻煩了,需要判斷l2是不是比l1長,最後還是選擇直接多新增一個list出來存結果。
/**
* 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));
struct ListNode* ptr=head;
int sum=0;
/*先宣告一個node存結果*/
ptr->next=NULL;
/*主要的迴圈*/
while(1){
/*如果l1或l2的node不是空的,就把結果加到sum*/
if(l1 != NULL){
sum+=l1->val;
l1=l1->next;
}
if(l2 != NULL){
sum+=l2->val;
l2=l2->next;
}
/*把結果存到這個結點*/
ptr->val=sum%10;
/*如果要進位的數值*/
sum/=10;
/*如果l1或l2 還有node沒處理完,或是最後還要進位,就新增node 繼續跑*/
if (l1 != NULL || l2 != NULL || sum != 0) {
struct ListNode* newnode=(struct ListNode*)malloc(sizeof(struct ListNode));
newnode->next=NULL;
ptr->next=newnode;
ptr=newnode;
} else break;
}
return head;
}