当前位置:网站首页>NC40 链表相加(二)
NC40 链表相加(二)
2022-08-09 13:02:00 【syc596】
NC40 链表相加(二)
链表相加(二)_牛客题霸_牛客网 (nowcoder.com)
2. 两数相加
import java.util.*;
public class Solution {
public ListNode reverse(ListNode head){
ListNode prev=null;
ListNode cur=head;
while(cur!=null){
ListNode next=cur.next;
cur.next=prev;
prev=cur;
cur=next;
}
return prev;
}
public ListNode addInList (ListNode head1, ListNode head2) {
head1=reverse(head1);
head2=reverse(head2);
ListNode vhead=new ListNode(-1);
ListNode cur=vhead;
int carry=0;
while(head1!=null||head2!=null){
int x=(head1==null)?0:head1.val;
int y=(head2==null)?0:head2.val;
int sum=x+y+carry;
carry=sum/10;
sum=sum%10;
cur.next=new ListNode(sum);
cur=cur.next;
if(head1!=null){
head1=head1.next;
}
if(head2!=null){
head2=head2.next;
}
}
if(carry==1){
cur.next=new ListNode(carry);
}
return reverse(vhead.next);
}
}边栏推荐
猜你喜欢

Anta and Huawei Sports Health jointly verify the champion running shoes and lead Chinese sports with innovation

微服务+微信小程序实现社区服务

阿里大淘系模型治理阶段性分享

render解析

GIN file upload and return

Clock frequency and baud rate count for serial communication in FPGA

群组行动控制--自动队列化实现策略

FFmpeg多媒体文件处理(ffmpeg处理流数据的基本概念)

5G China unicom AP:B SMS ASCII Transcoding Requirements

Explanation of RTSP protocol
随机推荐
kustomize入门示例及基本语法使用说明
时间序列分析课程实验报告
error Trailing spaces not allowed no-trailing-spaces 9:14 error Unexpected trailing comma
ArcEngine(九)图形绘制
[MRCTF2020]套娃-1
Q_06_05 文件结构
第六届”蓝帽杯“全国大学生网络安全技能大赛 半决赛
联通网管协议框图
农村区县域农业电商如何做?数字化转型如何进行?
FPGA - Summary of bugs in ISE (in update)
The sword refers to Offer 56 - II. Number of occurrences of a number in an array II (bit operation)
An Offer 21. Adjust the array in order to make odd in even the front (loop invariant)
Q_07 词汇表
01_iTween_第一天--小球抛物线
GIN Bind模式获取参数和表单验证
How to solve the 0x80070005 error when the computer is reinstalled and the system is restored
How to reduce the size of desktop icons after the computer is reinstalled
Realization of RTSP Protocol
Sandbox中的进程/线程相关-1
电脑重装系统还原0x80070005错误如何解决