/**
* @author lrx 2016年10月23日下午5:05:20
*/
/*
* 两个数字想加,每一位存在一个节点中,其实这道题用C写更好一点,因为c的链表毕竟熟悉
* 解题最重要的还是思路,自己先把所有的情况用自己的思路过一遍,然后再写代码
* 带吃饭共用时:3小时
*/
public class AddTwoSum {
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode l3 = new ListNode(-1);// 保存最终结果
ListNode tail = new ListNode(-1);// 永远指向结尾
int col = 0; // 进位
/*
* 设两个数字中最短数字长度length 这个循环将先length长度的数字加起来
*/
while (l1 != null && l2 != null) {
ListNode l4 = new ListNode(-1);
int sum = l1.val + l2.val + col;
if (sum > 9) {
col = 1;
l4.val = sum - 10;
//
} else {
col = 0;
l4.val = sum;
}
l1 = l1.next;
l2 = l2.next;
if (l3.val == -1) {
tail = l4;
l3 = tail;
} else {
tail.next = l4;
tail = tail.next;
}
}
/*
* 若两个数字长度相同,只需要加上进位即可
*/
if (l1 == null && l2 == null) {
if (col == 1) {
tail.next = new ListNode(1);
}
return l3;
}
/*
* t1 对l1进行循环的变量 t2 对l2进行循环的变量 tail2
*/
ListNode t1 = l1;
ListNode t2 = l2;
ListNode tail2;
/*
* 两个数字长度不同,加上进位接到l3结尾即可,l2长则执行if
*/
if (l1 == null) {
// System.out.println("t1==null");
tail2 = t2;
while (col == 1 && t2 != null) {// 有进位循环加到高位数字
t2.val += col;
if (t2.val > 9) {
col = 1;
t2.val -= 10;
} else {
col = 0;
}
t2 = t2.next;
if (t2 != null) {
tail2 = t2;
}
}
tail.next = l2;// 无进位直接连接高位数字
tail = tail2; // 指向最后一个节点
// 若最后还有进位,创建新节点 1 加入
if (col == 1) {
tail.next = new ListNode(1);
}
} else {
tail2 = t1;
while (col == 1 && t1 != null) {
t1.val += col;
System.out.println("t1.val=" + t1.val);
if (t1.val > 9) {
col = 1;
t1.val -= 10;
} else {
col = 0;
}
t1 = t1.next;
if (t1 != null) {
tail2 = t1;
}
}
tail.next = l1;
tail = tail2;
if (col == 1) {
tail.next = new ListNode(1);
}
}
return l3;
}// 16:55
public static void main(String[] args) {
ListNode l2 = new ListNode(2);
ListNode l1 = new ListNode(8);
ListNode t = null;
t = l1;
ListNode l = new ListNode(9);
t.next = l;
t = t.next;
ListNode l3 = addTwoNumbers(l1, l2);
while (l3 != null) {
System.out.println(l3.val);
l3 = l3.next;
}
}
}
改进思路:
设置进位变量 carry;
设置result;
循环直到两个链表都结束{
sum=节点相加+carry,若其中一个链表到头则值为零;
carry=sum/10;
新建节点=sum%10 并存入result;
两个链表都向下走一个节点;
}
若进位为一,新建节点并加入result;