/**
* 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 *result = &head; //结果链表以头结点起头
int flag = 0; //表示进位,初始化为0
int temp = 0; //表示相加的数,初始化为0
while ( l1 || l2 || flag ){ //两个链表都循环完毕,并且也没有进位
if (l1 != nullptr) //加l1
temp += l1->val;
if (l2 != nullptr) //加l2
temp += l2->val;
temp += flag; //加进位
//处理进位
flag = temp / 10;
temp = temp % 10;
ListNode *next = l1 ? l1 : l2; //将next置为恰当的节点
//当两个链表都循环完毕却还有进位的时候
if ( next == nullptr )
next = new ListNode(temp);
next->val = temp;
//将新的结果节点添加到结果链表中
result->next = next;
result = result->next;
//重新将相加结果置为0
temp = 0;
//循环l1和l2
l1 = l1 ? l1->next : nullptr;
l2 = l2 ? l2->next : nullptr;
}
//出去头结点,返回结果链表
return head.next;
}
};
letcode 2:Add Two Numbers
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Description: Given a string S, find the length of the lon...
- http://www.lintcode.com/en/problem/longest-common-substri...
- 题目: http://www.spoj.com/problems/LCS/ http://www.spoj.com...