题目
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.
思路
这道题就是在考链表,啥乱七八糟的关系搞清楚就行了,我也是懵了半天才反应过来。
另外需要注意的就是进位别把进位给搞丢了。
还有就是别忘了,给出的两个数可不一定等长,注意处理各种特殊情况,不过也不慌,坑踩多了就记住了。
代码
本人菜鸡,大佬们想看就看看,不想看也就那样
public class Add_Two_Numbers {
public static void main(String[] args) {
ListNode a = new ListNode( 2 );
ListNode b = new ListNode( 4 );
ListNode c = new ListNode( 3 );
ListNode d = new ListNode( 5 );
ListNode e = new ListNode( 6 );
ListNode f = new ListNode( 7 );
a.next = b;
b.next = c;
d.next = e;
e.next = f;
ListNode o = addTwoNumbers( a, d );
while( o != null ) {
System.out.print( o.val );
o = o.next;
}
}
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode first = new ListNode(0);
ListNode before = first;
int up = 0;
while( l1!=null || l2!=null || up!=0) {
if( l1!=null && l2!=null ) {
before.next = new ListNode( (l1.val + l2.val + up)%10 );
up = (l1.val + l2.val + up)/10;
l1 = l1.next;
l2 = l2.next;
}else if( l1==null && l2!=null ) {
before.next = new ListNode( (l2.val + up)%10 );
up = (l2.val + up)/10;
l2 = l2.next;
}else if( l1!=null && l2==null ) {
before.next = new ListNode( (l1.val + up)%10 );
up = (l1.val + up)/10;
l1 = l1.next;
}else if( l1==null && l2==null && up != 0 ) {
before.next = new ListNode( up );
up = 0;
}
before = before.next;
}
return first.next;
}
}
//节点
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}