解题思路:
取一个标记mark记录是否有进位,进位记为1否则为0;
1)先以第一条链表为基准,以相同顺序遍历第二条链表;计算相同节点值的和;
循环:
{ 1、 若第二条链表节点不为空,计算节点值和;
1.1判断sum是否大于10,若大于10,结果节点值val=sum-10,mark=1;增加结果链表节点
若小于10,val=sum,增加结果链表节点;继续遍历两条链表;
2.、第二条链表节点为空,只遍历第一条链表
重复1.1的操作
}
2)判断第二条连边是否遍历完全
重复1.1的操作
3)检查标记Mark是否为1
mark=1,则在结果,增加结果链表节点;val=1.
public class C_addTwoNumbers {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null && l2 == null) {
return null;
}
ListNode re = new ListNode(0);
ListNode h1 = new ListNode(0);
ListNode h2 = new ListNode(0);
h1.next = l1;
h2.next = l2;
ListNode p1 = h1;
ListNode p2 = h2;
ListNode p3 = re;
int mark = 0;
while (p1.next != null) {
if (p2.next != null) {
int sum = p1.next.val + p2.next.val + mark;// mark;
ListNode node = new ListNode(0);
if (sum < 10) {
node.val = sum;
p3.next = node;
p3 = p3.next;
p1 = p1.next;
p2 = p2.next;
mark = 0;
} else {
node.val = sum - 10;
p3.next = node;
p3 = p3.next;
p1 = p1.next;
p2 = p2.next;
mark = 1;
}
} else {
int sum = p1.next.val + mark;
ListNode node = new ListNode(0);
if (sum < 10) {//检查是否有进位
node.val = sum;
p3.next = node;
p3 = p3.next;
p1 = p1.next;
mark = 0;
} else {
node.val = sum - 10;
p3.next = node;
p3=p3.next;
p1 = p1.next;
}
}
}
// 验证第二条链表是否读完;
if (p2.next != null) {
while (p2.next != null) {
int sum = p2.next.val + mark;
if (sum < 10) {
ListNode node = new ListNode(0);
node.val = sum;
p3.next = node;
p3 = p3.next;
p2 = p2.next;
mark = 0;
} else {
ListNode node = new ListNode(0);
node.val = sum - 10;
p3.next = node;
p3 = p3.next;
p2 = p2.next;
mark = 1;
}
}
}
// 两条链表都已经读完,验证是否还有进位的值
if (mark != 0) {
ListNode node = new ListNode(0);
node.val = mark;
p3.next = node;
p3 = p3.next;
mark = 0;
}
return re.next;
}
}