版權聲明:本文為部落客原創文章,遵循 CC 4.0 BY-SA 版權協定,轉載請附上原文出處連結和本聲明。
本文連結:https://blog.csdn.net/shiliang97/article/details/101436465
題目描述
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 -> 8
Explanation: 342 + 465 = 807.
複制
我太難了,感覺自己C語言文法上咋都有這麼多問題呢~~~~各種指針異常,以前刷pat都沒遇到過。現在問題全都暴露出來了
先研究别人的優秀的代碼,快速的過一遍吧,回過頭來再看。反正資料結構啥的我都還沒有學呢~~~
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
int flag = 0, nodeSum = 0, freeflag = 0;
struct ListNode *ret,*now,*high,*freeBegin,*freeEnd;
for(ret = l1, now = l1, high = l2, freeBegin = l2;l1 || l2 || flag ;) {
if (l1 == NULL && l2 == NULL) {
now->next = high;
now = now->next;
freeBegin = now->next;
}
nodeSum = ( l1 ? l1->val : 0 ) + (l2 ? l2->val : 0) + flag;
now->val = nodeSum % 10;
flag = nodeSum / 10;
l1 ? l1 = (l1->next ? l1->next : NULL) : NULL;
if(l1 == NULL && 0 == freeflag && l2) {
freeEnd = l2;
freeflag = 1;
}
l2 ? l2 = (l2->next ? l2->next : NULL) : NULL;
now->next = ( l1 ? l1 : (l2 ? l2 : NULL) );
now->next ? now = now->next : NULL;
}
l2 = freeBegin;
freeEnd->next = NULL;
return ret;
}
複制