LeetCode之链表数相加
来源:互联网 发布:商品标签制作软件 编辑:程序博客网 时间:2024/06/02 20:08
问题描述:
/** * You are given two linked lists representing two non-negative numbers. * * The digits are stored in reverse order and each of their nodes contain a single digit. * * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) * * Output: 7 -> 0 -> 8 */
就是说有两个链表代表两个非负的整数,每一个链表节点都存储一个单个的数字,并且节点存储的顺序和整数的数字排列顺序是相反的,如上所示,数a为342,数b为465,相加为807.
解题思想还是从数的末尾开始相加,对于这道题来说也就是从两个链表的开头进行运算,期间要声明一个变量来作为进位。
这道题和我前面一篇博客是类似的,在进行运算时要对两个数“对齐”,即在对齐的情况下是一种运算,不对齐又是另一种情况。下面是代码:
public class AddTwoNumbers { public static ListNode addTwoNumbers(ListNode l1, ListNode l2) { if (l1 == null) return l2; if (l2 == null) return l1; ListNode head = new ListNode(0); ListNode cur = head; int plus = 0; while (l1 != null && l2 != null) { int sum = l1.val + l2.val + plus; plus = sum / 10; sum = sum % 10; cur.next = new ListNode(sum); cur = cur.next; l1 = l1.next; l2 = l2.next; } if (l1 != null) { if (plus != 0) { cur.next = addTwoNumbers(l1, new ListNode(plus)); } else { cur.next = l1; } } else if (l2 != null) { if (plus != 0) { cur.next = addTwoNumbers(l2, new ListNode(plus)); } else { cur.next = l2; } } else if (plus != 0) { cur.next = new ListNode(plus); } return head.next; } public static void main(String args[]) { ListNode l1=new ListNode(2); l1.next=new ListNode(4); l1.next.next=new ListNode(3); ListNode r1=new ListNode(5); r1.next=new ListNode(6); r1.next.next=new ListNode(4); ListNode newnode=addTwoNumbers(l1,r1); while(newnode!=null) { System.out.println(newnode.val); newnode=newnode.next; } }}
在声明Listnode时,竟然感觉有点吃力,忘了数据结构是怎么样的了,然后查了一下才解决,其实,用java声明单链表是很简单的,如下所示:
public class ListNode { int val; ListNode next; public ListNode(int x){ val = x; next = null; }}
0 0
- LeetCode之链表数相加
- leetcode 之 二进制数相加
- LeetCode之二进制字符串相加
- leetCode 之 两个二进制数相加
- [Leetcode]Add Two Numbers链表数相加
- LeetCode OJ 之 Add Binary (二进制数字相加)
- LeetCode OJ 之 Add Two Numbers (”两数“相加)
- LeetCode OJ 之 Add Digits (数字相加)
- [LeetCode]67 二进制相加
- Add Binary 二进制相加 @LeetCode
- Leetcode:Add Binary 二进制相加
- [LeetCode]2 两个数相加
- Leetcode 第二题,两数链表相加
- 【LeetCode】 Add Digits 数字相加
- 大数相加之我见
- LintCode之各位相加
- LeetCode 之 two Sum寻找两个相加之和为给定值的两个数
- leetcode解题之258# Add Digits Java版 (相加各个位数)
- Android Fragment 真正的完全解析(上)
- Java 顺时针打印矩阵
- 【hadoop】Hadoop,MapReduce操作Mysql(比较早的操作方法,可以看看)
- 短信发送倒计时(以及正则验证)
- android中不依赖activity的dialog弹窗的实现
- LeetCode之链表数相加
- fopen() / fscanf() / fprintf() / fclose()
- 2016长乐夏令营 Day4
- easy ui 行内编辑数据并保存
- 供应链协同采购的需求分析与实现方法
- ajax提交表单问题
- today
- android,NDK, write logs to a file
- 自定义PopupWindow实现底部弹出式菜单