https://leetcode-cn.com/problems/sum-lists-lcci/
思路:反向存放比较简单,模拟就行了。考虑进阶怎么做? ( 1 ) (1) (1)先翻转链表,再利用相同的办法处理; ( 2 ) (2) (2)利用栈。注意 ( 1 ) (1) (1)会对原链表进行修改。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode head(0);
ListNode *pre=&head,*cur;
int val=0,jw=0;
while(l1||l2||jw){
val=jw;
if(l1)
val+=l1->val,l1=l1->next;
if(l2)
val+=l2->val,l2=l2->next;
jw=val/10;
cur=new ListNode(val%10);
pre->next=cur;
pre=cur;
}
return head.next;
}
};