【题目】假设链表中每一个节点的值都在0~9之间,那么链表整体就可以代表一个整数。
例如:9->3->7,可以代表整数937.
给定两个两个这种链表的头结点head1和head2,请生成代表两个整数相加值的结果链表。
例如:链表1为9->3->7,链表2为6->3,最后生成新的结果链表为1->0->0->0。
public class TwoLinkedlistAdd {
public static class Node {
public int value;
public Node next;
public Node(int value) {
this.value = value;
}
}
public static Node twoLinkedListAdd(Node head1, Node head2) {
head1 = reverse(head1);
head2 = reverse(head2);
int ca = 0;
Node c1 = head1;
Node c2 = head2;
int n1 = 0;
int n2 = 0;
int n = 0;
Node node = null;
Node pre = null;
while (c1 != null || c2 != null) {
n1 = c1 == null ? 0 : c1.value;
n2 = c2 == null ? 0 : c2.value;
n = n1 + n2 + ca;
pre = node;
node = new Node(n % 10);
node.next = pre;
ca = n / 10;
c1 = c1 != null ? c1.next : null;
c2 = c2 != null ? c2.next : null;
}
if (ca == 1) {
pre = node;
node = new Node(1);
node.next = pre;
}
reverse(head1);
reverse(head2);
return node;
}
public static Node reverse(Node head) {
Node pre = null;
Node next = null;
while (head != null) {
next = head.next;
head.next = pre;
pre = next;
head = next;
}
return head;
}
}