描述
假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。
给定两个这种链表,请生成代表两个整数相加值的结果链表。
例如:链表 1 为 9->3->7,链表 2 为 6->3,最后生成新的结果链表为 1->0->0->0。
示例1
输入:
[9,3,7],[6,3]
复制
返回值:
{1,0,0,0}
public class 两个链表生成相加链表 {
public class ListNode {
int val;
ListNode next = null;
public ListNode(int i) {
val = i;
}
}
// public ListNode addInList (ListNode head1, ListNode head2) {
// // write code here
// StringBuilder sb1 = new StringBuilder();
// while(head1 != null){
// sb1.append(head1.val);
// head1 = head1.next;
// }
// StringBuilder sb2 = new StringBuilder();
// while(head2 != null){
// sb2.append(head2.val);
// head2 = head2.next;
// }
// String result = String.valueOf(new BigDecimal(sb2.toString()).add(new BigDecimal(sb1.toString())).toPlainString());
// System.out.println(result);
// ListNode temp = new ListNode(-1);
// ListNode curr = new ListNode(result.charAt(0) - 48);
// for(int i = 1; i < result.length();i++){
// curr.next = new ListNode(result.charAt(i) - 48);
// curr = curr.next;
// }
// return temp.next;
// }
public ListNode reverse(ListNode head){
if(head == null || head.next == null){
return head;
}
ListNode pre = null, curr = head;
while(curr != null){
ListNode temp = curr.next;
curr.next = pre;
pre = curr;
curr = temp;
}
return pre;
}
public ListNode addInList (ListNode head1, ListNode head2) {
// write code here
ListNode h1 = reverse(head1), h2 = reverse(head2);
ListNode temp = new ListNode(-1);
ListNode curr = temp;
boolean flag = false;
int t = 0;
while(h1 != null || h2 != null){
int node1 = h1 != null ? h1.val : 0;
int node2 = h2 != null ? h2.val : 0;
int total = node1 + node2;
if(flag){
total += 1;
}
if(total / 10 > 0){
flag = true;
}else{
flag = false;
}
curr.next = new ListNode(total % 10);
if(h1 != null){
h1 = h1.next;
}
if(h2 != null){
h2 = h2.next;
}
curr = curr.next;
}
if(flag){
curr.next = new ListNode(1);
}
return reverse(temp.next);
}
}