leetcode-2 Add Two Numbers
来源:互联网 发布:数据挖掘有什么作用 编辑:程序博客网 时间:2024/06/05 21:07
leetcode-2 Add Two Numbers
思路:
1. 定义两个游标迭代器,分别初始化为指向链表头部l1,l2;
2. 从头部开始扫描l1和l2,两个游标指示元素相加之和取个位与进位相加,得到的值作为当前位的结果保存,并根据实际情况进行进位操作,如果某个游标先结束,则该游标及其后继都被标记为NULL;
3. 判断最后一位是否有进位,如果有,把最后一个进位最为最高位保存下来;
4. 返回最终链表的真实头指针(代码中加入了一个空的头结点,是为了便于代码迭代步骤的统一性);
源码如下:
/*** 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* cursor1 = l1; ListNode* cursor2 = l2; ListNode* cursor3 = new ListNode(0); ListNode* l3 = cursor3; ListNode* temp = NULL; int val1=0,val2 = 0; bool incre = false; int lowAdd = 0; while (cursor1 != NULL || cursor2 != NULL) { val1 = cursor1!=NULL?cursor1->val : 0; val2 = cursor2!=NULL?cursor2->val :0; temp = new ListNode(0); temp->val = val1 + val2 + lowAdd; temp->val <10 && (incre = false); temp->val >= 10 && (temp->val -= 10, incre = true); cursor3->next = temp; cursor3 = temp; temp = NULL; lowAdd = incre ? 1 : 0; cursor1 = cursor1!=NULL? cursor1->next : NULL; cursor2 = cursor2!=NULL? cursor2->next : NULL; } incre && (cursor3->next = new ListNode(lowAdd)); cursor3= NULL; l3 = l3->next; delete cursor3; //reverseNodes(l1); return l3; } void reverseNodes(ListNode* &l) { ListNode* cursor = l; ListNode* temp = NULL; l = NULL; while (cursor != NULL) { temp = cursor->next; cursor->next = l; l = cursor; cursor = temp; } }};
阅读全文
0 0
- LeetCode 2 - Add Two Numbers
- LeetCode 2: Add Two Numbers
- Leetcode: Add Two Numbers (2)
- [leetcode 2] Add Two Numbers
- [Leetcode] 2 - Add Two Numbers
- LeetCode 2:《Add Two Numbers》
- LeetCode | #2 Add Two Numbers
- LeetCode 2 Add Two Numbers
- [Leetcode]2Add Two Numbers
- leetcode #2 Add Two Numbers
- leetcode-2 Add Two Numbers
- LeetCode 2 Add Two Numbers
- [leetcode] #2 Add Two Numbers
- LeetCode-2 Add Two Numbers
- LeetCode-2-Add Two Numbers
- Leetcode[2] Add Two Numbers
- LeetCode 2 Add Two Numbers
- LeetCode 2 Add Two Numbers
- 内容提供者2
- centos7下解压缩与跨服务器传输文本那些事儿
- 第九周项目实践2 二叉树遍历的递归算法
- OAuth简介
- MAVEN基础配置文件的简单介绍
- leetcode-2 Add Two Numbers
- 对象结构型模式——适配器模式(adapter)
- linux之sort用法
- 理解java Web项目中的路径问题
- json对象格式
- 数据结构与算法C++描述(10-插曲)---函数名作形参
- 二维码的生成细节和原理
- 好用的maven镜像
- 房屋买卖合同纠纷中解约定金的适用