Leetcode - Add Two Numbers

来源:互联网 发布:js typeof function 编辑:程序博客网 时间:2024/05/20 06:55

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
   public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1==null || l2==null){
return l1==null?l1:l2;
}
ListNode ln = null, prev = ln, first = null;
boolean over = false;
while (l1 != null && l2 != null) {
int x = over ? l1.val + l2.val + 1 : l1.val + l2.val;
over = x / 10 >= 1;
ln = new ListNode(x % 10);
l1 = l1.next;
l2 = l2.next;
if (prev == null)
prev = ln;
else{
prev.next = ln;
prev= prev.next;
}

if (first == null)
first = prev;
}


append(l1!=null ? l1: l2, over, prev);

return first;
}
public void append(ListNode l, boolean over, ListNode prev){
while (l != null) {
int y = over ? l.val + 1 : l.val;
over = y / 10 >= 1;
ListNode ln = new ListNode(y % 10);
l=l.next;
prev.next = ln;
prev= prev.next;
}

if(over){
    ListNode ln = new ListNode(1);
prev.next = ln;
prev= prev.next;
}
}
}

--------------------------

HINT: 链表的使用,思路清晰+表达

=========================

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

0 0
原创粉丝点击