/**
* 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...