问题描述:
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
该问题实际上是解决大数相加的一种方法---通过链表来实现大数相加,博主在本科毕业参加一些企业的笔试时就遇到过这个问题。这个问题看似简单,实际上还是有些细节需要注意,主要是进位。
下面是通过测试的代码:
/** * 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) { int carry = 0; //进位 int digit = 0; ListNode* head = NULL; ListNode* pre = NULL; ListNode* newNode = NULL; while(l1 !=NULL && l2!=NULL) { digit = (l1->val+l2->val+carry)%10; carry = (l1->val+l2->val+carry)/10; newNode = new ListNode(digit); if (head == NULL) head = newNode; else pre->next = newNode; pre = newNode; l1 = l1->next; l2 = l2->next; } while (l1 != NULL) { digit = (l1->val+carry)%10; carry = (l1->val+carry)/10; newNode = new ListNode(digit); if (head == NULL) head = newNode; else pre->next = newNode; pre = newNode; l1 = l1->next; } while (l2 != NULL) { digit = (l2->val+carry)%10; carry = (l2->val+carry)/10; newNode = new ListNode(digit); if (head == NULL) head = newNode; else pre->next = newNode; pre = newNode; l2 = l2->next; } if(carry>0) { newNode = new ListNode(carry); pre->next = newNode; } return head; } };
原文:http://blog.csdn.net/computerme/article/details/44679729