题目: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
分析:两个链表存储数字,每个链表类似于十进制存储,但是是逆序存储,如2->4->3类似于十进制的342,求出这两个链表的和,返回一个新链表。
从左到右,直接每位相加,结果大于10则产生进位即可。
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 12 if(l1==NULL) 13 return l2; 14 if(l2==NULL) 15 return l1; 16 ListNode *result = NULL,*temp = NULL; 17 ListNode *p=l1,*q=l2; 18 int addResult = 0,carry = 0; //carry记录进位,addResult记录对应位置数字相加的和 19 while(p&&q){ 20 addResult = p->val + q->val + carry; 21 carry = addResult/10; 22 if(result == NULL){ 23 result = new ListNode(addResult%10); 24 temp=result; 25 }else{ 26 temp->next = new ListNode(addResult%10); 27 temp = temp->next; 28 } 29 p=p->next; 30 q=q->next; 31 } 32 while(p){ 33 addResult = p->val + carry; 34 carry = addResult/10; 35 temp->next = new ListNode(addResult%10); 36 temp = temp->next; 37 p=p->next; 38 } 39 while(q){ 40 addResult = q->val + carry; 41 carry = addResult/10; 42 temp->next = new ListNode(addResult%10); 43 temp = temp->next; 44 q=q->next; 45 } 46 if(carry>0){ //当两条链表全部遍历结束,如果进位不为0,则在result链表尾部应继续创造一个结点,存储该进位carry 47 temp->next = new ListNode(carry); 48 } 49 return result; 50 } 51 };