LeetCode 2. Add Two Numbers
题目描述:
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.
思路分析
这个题其实没有什么特别,对应的链表结点进行加法运算就行,只不过需要进行记录有无进位。存在一个新的链表里面就可以,这就需要开辟新空间(new操作),如果链表为空,则认为结点中的值为0,方便进行计算。程序比较简单。
具体代码:
/**
* 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) {
if(l1==NULL&&l2==NULL)
return NULL;
//注意进位应该就行
ListNode* dumy=new ListNode(0);
ListNode* p=dumy;
int flag=0; //进位标志
while(l1||l2||flag)
{
int sum=(l1!=NULL?l1->val:0)+(l2!=NULL?l2->val:0)+flag;
flag=sum/10;
p->next=new ListNode(sum%10);
p=p->next;
l1 = (l1!=NULL) ? l1->next : l1;
l2 = (l2!=NULL) ? l2->next : l2;
}
return dumy->next;
}
};