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.
可以对比网上其它解法: http://www.2cto.com/kf/201310/252996.html
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Subscribe to see which companies asked this question
题目链接:https://leetcode.com/problems/add-two-numbers/
读清题意:
9 5 8
+2
有 11 5 8 ---------->1 6 8
9 5 8
+ 7 6 4
有 16 11 12------------->6 2 3 1
package temp;
/**
*
* @author Mouse
*
*/
public class Solution {
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null)
return l2;
if (l2 == null)
return l1;
ListNode p = l1;
ListNode ps=p;
ListNode q = l2;
int flag = 0;// 进位
while (p != null && q != null) {
if (p.val + q.val + flag >= 10) {
p.val = p.val + q.val + flag - 10;
flag = 1;// 表示有进位
} else {
p.val = p.val + q.val + flag;
flag = 0;
}
ps=p;
p = p.next;
q = q.next;
}
// 处理p与q不相等的情况
if (q != null) {
ps.next=q;
p=q;
}
if (flag > 0) {
while (p != null) {
if (p.val + flag >= 10) {
p.val = p.val + flag - 10;
flag = 1;// 表示有进位
} else {
p.val = p.val + flag;
flag = 0;
}
ps=p;
p = p.next;
}// while
}// if
if (flag > 0) {// 链表最后一个flag如果仍然为1说明有进位
ListNode temp = new ListNode(1);
ps.next = temp;
}// if
return l1;
}
public static void main(String[] args) {
ListNode l1 = new ListNode(0);
//ListNode l10 = new ListNode(4);
//ListNode l11 = new ListNode(3);
//l1.next = l10;
//l10.next = l11;
ListNode l2 = new ListNode(7);
ListNode l20 = new ListNode(3);
//ListNode l21 = new ListNode(4);
l2.next = l20;
//l20.next = l21;
ListNode p = addTwoNumbers(l1, l2);
ListNode q = p;
while (q != null) {
System.out.print(" " + q.val);
q = q.next;
}
}
}
可以对比网上其它解法: http://www.2cto.com/kf/201310/252996.html