You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
- Example:
- Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
- Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
题意大致就是给定两个链表按照加法进行运算, 因为是链表所以最后需要进行一次链表的翻转才能得到预期的结果这是需要注意的
因为 leet 限制了数据结构并且不希望我们改变他的数据结构, 所以我们不能自定义链表的实现只能用他们定义的链表实现功能
定义如下
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
这道题并不复杂来看 一看笔者的初始实现代码
- public class Solution2 {
- ListNode dummyHead = new ListNode(0);
- public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
- int mod = 0;
- while (true) {
- int var1 = 0, var2 = 0;
- if (l1 != null) {
- var1 = l1.val;
- l1 = l1.next;
- }
- if (l2 != null) {
- var2 = l2.val;
- l2 = l2.next;
- }
- int sum = var1 + var2 + mod;
- ListNode pre = dummyHead;
- ListNode current = new ListNode(sum % 10);
- current.next = pre.next;
- pre.next = current;
- mod = sum / 10;
- if (l1 == null && l2 == null) {
- break;
- }
- }
- if (mod != 0) {
- ListNode pre = dummyHead;
- ListNode current = new ListNode(mod);
- current.next = pre.next;
- pre.next = current;
- }
- // 反转链表
- return reverseList(dummyHead.next);
- }
- public ListNode reverseList(ListNode head) {
- if (head == null)
- return head;
- ListNode dummyHead = new ListNode(0);
- dummyHead.next = head;
- ListNode pre = head;
- ListNode current = pre.next;
- while (current != null) {
- pre.next = current.next;
- current.next = dummyHead.next;
- dummyHead.next = current;
- current = pre.next;
- }
- return dummyHead.next;
- }
- public class ListNode {
- int val;
- ListNode next;
- ListNode(int x) {
- val = x;
- }
- }
- }
提交后发现:
- Runtime: 2 ms, faster than 100.00% of Java online submissions for Add Two Numbers.
- Memory Usage: 46 MB, Less than 55.21% of Java online submissions for Add Two Numbers.
从时间复杂度来说这是一个 O(n) 复杂度的度算法, 暂无优化空间
空间复杂度相对来说在容忍范围
来源: http://www.jianshu.com/p/f5337f0e6fa8