面试题:Add Two Numbers(模拟单链表)
2024-10-20 18:49:29
题干:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
注:
题目中链表的定义为
public class ListNode {
int val;
ListNode next; ListNode(int val) {
this.val = val;
}
}
分析:
题干中链表中的数是倒序存储的,题干中给的例子其实是:342+465=807。
我们定义一个节点dummyHead来指向结果的头结点,然后定义三个节点p,q,curr分别用来记录l1当前节点,l2当前节点,结果当前节点。
定义int carry来记录是否有进位。
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode p = l1, q = l2, curr = dummyHead;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null)
p = p.next;
if (q != null)
q = q.next;
}
if (carry > 0) {
curr.next = new ListNode(carry);
}
return dummyHead.next;
}
最新文章
- 创建agsXMPP 自定义packet types
- c = (a / b, a%b) 运算输出顺序
- 让Entity Framework启动不再效验__MigrationHistory表
- jQuery 根据城市时区,选择对应的即时时间
- 解压和生成 system.img&;data.img ( ext4格式)
- MYSQL delete 从多人表中删除
- tiny4412学习笔记-将uboot、zImage、文件系统烧到emmc中
- Android破解心得——记学习七少月安卓大型安全公开课
- react 或 vue 中引用 jQuery 插件
- Windows获取进程完整路径
- docker+springboot+elasticsearch+kibana+elasticsearch-head整合(详细说明 ,看这一篇就够了)
- r里面如何实现两列数据合并为一列
- Flask 中的 CBV 与上传文件
- bzoj1477: 青蛙的约会(exgcd)
- 天天爱跑步&;&;弹球
- ubuntu12.04下Qt调试器的使用
- HTIML5 真的打败了Flash?新测试结果出人意料
- ERROR - Undefined placeholders found in template:
- [转]C结构体之位域(位段)
- BFS搜索:POJ No 3669 Meteor Shower
热门文章
- 三十道DP练习(持续更新)(pw:DP)
- freebsd网卡驱动程序详解
- [ARC068F] Solitaire [DP]
- ubuntu安装出现";删除initramfs-tools时出错";,subprocess installed post-installation script returned error exit status 1
- Codeforces 932.A Palindromic Supersequence
- SpringMVC+MyBatis+Shiro 配置文件详解
- MyBatis的常见错误总结
- ACdream 1210	Chinese Girls' Amusement(高精度)
- Scenes in Cocos2D
- Golang/Go语言/Go IDE/Go windows环境搭建/Go自动提示编译器/GoSublime