You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 8 -> 0 -> 7
题目链接:https://leetcode.com/problems/add-two-numbers-ii/
三次reverse,击败100%
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = head;
ListNode cur = head.next;
head.next = null;
while (cur != null) {
ListNode nxt = cur.next;
cur.next = pre;
pre = cur;
cur = nxt;
}
return pre;
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
l1 = reverseList(l1);
l2 = reverseList(l2);
ListNode helper = new ListNode(0);
ListNode tmp = helper;
int extra = 0;
while (l1 != null || l2 != null || extra != 0) {
int val1 = l1 == null ? 0 : l1.val;
int val2 = l2 == null ? 0 : l2.val;
helper.next = new ListNode((val1 + val2 + extra) % 10);
extra = (val1 + val2 + extra) / 10;
l1 = l1 == null ? l1 : l1.next;
l2 = l2 == null ? l2 : l2.next;
helper = helper.next;
}
return reverseList(tmp.next);
}
}

305

被折叠的 条评论
为什么被折叠?



