LeetCode #002 Add Two Numbers
来源:互联网 发布:解放台湾 知乎 编辑:程序博客网 时间:2024/04/30 00:58
002 Add Two Numbers
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路:
- 建立一个新的链表List
- 依次检测两个链表节点是否为空,不为空则检测值
- 如果检测到值,
int value = val1 + val2 + remain;
- val1=l1->val,val2=l2->val,它们被初始化为0,remain为进位值.
- 将value存入List节点里
代码:
/** * 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) { int remain = 0; //new list ListNode* head = new ListNode(0);//head node,it is empty. ListNode* p = head; if(l1==NULL && l2==NULL){ return NULL; } else if(l1==NULL && l2!=NULL){ return l2; } else if(l1!=NULL && l2==NULL){ return l1; } while(l1 != NULL || l2 != NULL)//only two list get end,while will be finish. { int val1 = 0, val2 = 0; if(l1 != NULL) { val1 = l1->val; } if(l2 != NULL) { val2 = l2->val; } int value = val1 + val2 + remain; remain = 0; if(value >= 10) { value -= 10;//value = value % 10 remain = 1; } //build List ListNode * pos = new ListNode(value); p->next = pos; p = p->next; if(l1 != NULL) l1 = l1->next; if(l2 != NULL) l2 = l2->next; } /* if ABCDE if FGHIG AND IF E+G>10 we need make a new node,it's val is (E+G)%10. like this: */ if(remain != 0) { ListNode* pos = new ListNode(remain); p->next = pos; } return head->next; //!!!__Don't return head because head is empty,head->next is first node with val.}};*/
知识点
- 如何用尾插法建立链表
- 同时遍历两个链表并进行相应处理(均遍历到结尾时处理才结束)
- 当遍历A节点时,得到需要处理A->next的信息,如何在遍历时延后一步处理。
- 方案1:用一个Bool量标记是否应当处理,在建表后的语句中加入处理语句
- 方案2:类似这种求和,将信息保留在remain中,每次加上remain,无信息则remain=0,否则remain=溢出数.
//方案1 bool deal=false; while(true){ ....//here you build list if(deal){ ....//here you deal something } } //方案2 int value = val1 + val2 + remain;
0 0
- 【leetcode】002 Add Two Numbers
- LeetCode 002 Add Two Numbers
- LeetCode 002-Add Two Numbers
- [LeetCode]-002-Add Two Numbers
- LeetCode #002 Add Two Numbers
- LeetCode 002, Add Two Numbers
- 002 Add Two Numbers [Leetcode]
- LeetCode 002 Add Two Numbers
- 002 Add Two Numbers [Leetcode]
- LeetCode #002 Add Two Numbers
- LeetCode 002 Add Two Numbers
- leetcode-002 Add Two Numbers
- 【Leetcode】002 Add Two Numbers
- LeetCode-002 Add Two Numbers
- leetcode 002 Add Two Numbers
- LeetCode: Add Two Numbers
- LeetCode: Add Two Numbers
- [LeetCode]Add Two Numbers
- 第七章 图形程序设计
- 最全前端面试问题及答案总结
- 道理你都懂,为什么你还会痛苦
- [华为机试练习题]56.求子数组的最大和
- js lodash 'date' 'nunber' 'math' methods
- LeetCode #002 Add Two Numbers
- 黑马程序员——Java集合框架—整理笔记
- Python_Monkeyrunner
- 《java课程设计》之猜猜看游戏(三)
- UIButton和UISlider
- Linux系统用到命令积累
- wget的下载与安装使用
- 每天学习一点新东西--vim篇(一)
- 【字符串数据结构后缀系列Part1】后缀数组学习笔记