NC40 两个链表生成相加链表
描述
假设链表中每一个节点的值都在 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) {
// write code here
if(head1 == null && head2 == null){
return null ;
}
if(head1 == null ){
return head2 ;
}
if(head2 == null){
return head1 ;
}
head1 = reverse(head1) ;
head2 = reverse(head2) ;
ListNode dummy = new ListNode(-1);
ListNode prev = dummy ;
int curt = 0 ;
while(head1 != null || head2 != null){
int a , b ;
if(head1 == null){
a = 0 ;
}else{
a = head1.val ;
}
if(head2 == null){
b = 0 ;
}else{
b = head2.val ;
}
int res = curt + a + b ;
if(res >= 10){
curt = 1 ;
}else{
curt = 0 ;
}
prev.next = new ListNode(res % 10) ;
prev = prev.next ;
if(head1 != null){
head1 = head1.next ;
}
if(head2 != null){
head2 = head2.next ;
}
}
if(curt != 0){
prev.next = new ListNode(1) ;
}
return reverse(dummy.next);
}
public ListNode reverse(ListNode head){
ListNode pred = null ;
while(head != null){
ListNode temp = head.next ;
head.next = pred ;
pred = head ;
head = temp ;
}
return pred ;
}
}
博客围绕 NC40 两个链表生成相加链表问题展开,假设链表节点值在 0 - 9 之间,链表可代表整数,需生成两个链表所代表整数相加值的结果链表,并给出了示例输入和返回值。
6117

被折叠的 条评论
为什么被折叠?



