题目描述:
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.
将两个链表里各节点的数相加,进位的进位,看例子就明白了。
解题思路:
这题的思路没有什么好说的,就是两个链表的数一个一个加起来。
代码:
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 ListNode* head=new ListNode(0); 13 ListNode* cur=head; 14 int carry=0; 15 while(l1!=NULL||l2!=NULL||carry){ 16 //l1,l1,进位都不存在时,出循环 17 int num1=0,num2=0; 18 if(l1){ 19 //l1存在是进行赋值,下同 20 num1=l1->val; 21 l1=l1->next; 22 } 23 if(l2){ 24 num2=l2->val; 25 l2=l2->next; 26 } 27 num1+=num2+carry;//用num1存三个数的和 28 cur->next=new ListNode(num1%10); 29 carry=num1/10; 30 cur=cur->next; 31 } 32 return head->next; 33 } 34 };
他人代码:
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 ListNode* head=new ListNode(0); 13 ListNode* cur=head; 14 int carry=0; 15 while(l1!=NULL||l2!=NULL||carry){ 16 int n = (l1?l1->val:0) + (l2?l2->val:0) + carry;//运用了三目运算符使代码更简洁 17 cur -> next = new ListNode(n % 10); 18 carry = n / 10; 19 cur = cur -> next; 20 l1 = l1?l1 -> next:NULL; 21 l2 = l2?l2 -> next:NULL; 22 } 23 return head->next; 24 } 25 };