【leetcode】Add Two Numbers
来源:互联网 发布:手机版淘宝店铺收藏 编辑:程序博客网 时间:2024/06/04 17:55
描述:
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
/** * 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) { return l2; } else if(l2 == NULL) { return l1; } /*两个链表的结点值相加,用l1存储和结点*/ ListNode *p = l1, *q = l2; ListNode *last = l1; int carry = 0; while(p != NULL && q != NULL) { p->val += (q->val+carry); carry = p->val/10; p->val %= 10; last = p; p = p->next; q = q->next; } /*l2的数比l1大,将剩余的高位结点连缀至l1尾部*/ if(q != NULL) { last->next = q; p = q; } /*只考虑剩余高位结点数字和进位的和*/ while(p != NULL) { p->val += carry; /*某一低位和进位的和未超过10,则后续高位不会因为进位而进一步产生进位*/ if(p->val < 10) { carry = 0;/*注意:一定要置零*/ break; } carry = p->val/10; p->val %= 10; last = p; p = p->next; } /*当高位结点用完,还有进位时,开辟一个新的结点*/ if(carry != 0) { ListNode *tmp = (ListNode*)malloc(sizeof(ListNode)); tmp->val = carry; tmp->next = NULL; last->next = tmp; } return l1; }};
分析:
时间复杂度:O(m+n)
空间复杂度:O(1)
0 0
- LeetCode: Add Two Numbers
- LeetCode: Add Two Numbers
- [LeetCode]Add Two Numbers
- LeetCode Add Two Numbers
- Leetcode: Add Two Numbers
- LeetCode : Add Two Numbers
- LeetCode Add Two Numbers
- [LeetCode] Add Two Numbers
- Leetcode : Add Two Numbers
- 【leetcode】Add Two Numbers
- [LeetCode]Add Two Numbers
- leetcode Add Two Numbers
- LeetCode-Add Two Numbers
- [leetcode] Add Two Numbers
- [LeetCode] Add Two Numbers
- LeetCode - Add Two Numbers
- LeetCode | Add Two Numbers
- 【leetcode】Add Two Numbers
- Myeclipse 使用总结
- 工作半年记
- Ubuntu下截图软件 - Shutter
- 写程序笔记
- android设计模式--之原型模式(prototype)
- 【leetcode】Add Two Numbers
- Android ProgressBar 自定义样式(六),仿真QQ pad版加载(位置居中)
- 用户注册时的格式化判断函数
- NYoj-喷水装置(二)
- HTML form 避免(回车)表单自动提交
- Leetcode Unique Paths II
- 2.1 Git 基础 - 取得项目的 Git 仓库
- 安装基于虚拟用户的虚拟域邮件服务器系统
- MyEclipse 快捷键