假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。
给定两个这种链表,请生成代表两个整数相加值的结果链表。
例如:链表 1 为 9->3->7,链表 2 为 6->3,最后生成新的结果链表为 1->0->0->0。
示例1
输入:
[9,3,7],[6,3]
复制
返回值:
{1,0,0,0}
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
public ListNode addInList (ListNode head1, ListNode head2) {
if(head1 == null){
return head2;
}
if(head2 == null){
return head1;
}
//1.需要将两个链表反转,然后再进一步求和
ListNode Head1 = ReverseListNode(head1);
ListNode Head2 = ReverseListNode(head2);
//2.定义一个新链表来接受两个链表的和
ListNode head = new ListNode(-1);
ListNode newHead = head;
int tmp = 0; //定义一个变量来记录进位
while(Head1 != null || Head2 != null){
int val = tmp; //用val来记录两个链表的和
if(Head1 != null){
val += Head1.val;
Head1 = Head1.next;
}
if(Head2 != null){
val += Head2.val;
Head2 = Head2.next;
}
tmp = val / 10;
ListNode node = new ListNode(val % 10);
newHead.next = node;
newHead = newHead.next;
}
if(tmp > 0){
newHead.next = new ListNode(tmp);
}
return ReverseListNode(head.next);
}
public ListNode ReverseListNode(ListNode head){
if(head == null){
return null;
}
ListNode prev = null;
ListNode cur = head;
while(cur != null){
ListNode curNext = cur.next;
cur.next = prev;
prev = cur;
cur = curNext;
}
return prev;
}
}