题地址:链表相加(二)_牛客题霸_牛客网
描述
假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。
给定两个这种链表,请生成代表两个整数相加值的结果链表。
数据范围:0 \le n,m \le 10000000≤n,m≤1000000,链表任意值 0 \le val \le 90≤val≤9
要求:空间复杂度 O(n)O(n),时间复杂度 O(n)O(n)
例如:链表 1 为 9->3->7,链表 2 为 6->3,最后生成新的结果链表为 1->0->0->0。
示例1
输入:
[9,3,7],[6,3]
复制返回值:
{1,0,0,0}
复制说明:
如题面解释
示例2
输入:
[0],[6,3]
复制返回值:
{6,3}
复制
备注:
1 \leq n, m \leq 10^61≤n,m≤106 0 \leq a_i, b_i \leq 90≤ai,bi≤9
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) {
head1 = getNode(head1);
head2 = getNode(head2);
ListNode head3 = new ListNode(-1);
ListNode head4 = head3;
int v = 0;
while (head1 != null || head2 != null) {
int a = 0;
a = a + v;
v = 0;
if (head1 != null) {
a = head1.val+a;
head1 = head1.next;
}
if (head2 != null) {
a = a + head2.val;
head2 = head2.next;
}
if (a >= 10) {
v = 1;
a = a - 10;
}
ListNode ln = new ListNode(a);
head3.next = ln;
head3 = ln;
}
if(v==1){
ListNode ln = new ListNode(1);
head3.next = ln;
}
head4 = getNode(head4.next);
return head4 ;
}
public ListNode getNode(ListNode head) {
ListNode pre = null;
while (head.next != null) {
ListNode now = head.next;
head.next = pre;
pre = head;
head = now;
}
head.next = pre;
return head;
}
public String sout(ListNode head){
String a = "";
while(head!=null){
a = a + head.val+",";
head = head.next;
}
return a;
}
}