add-two-numbers(单链表相加)
2017-04-10 21:38
330 查看
题目描述
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. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
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. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode newNode = new ListNode(0); ListNode node = newNode; int cap = 0; while(l1 != null || l2 != null) { if(l1 != null) { cap += l1.val; l1 = l1.next; } if(l2 != null) { cap += l2.val; l2 = l2.next; } node.next = new ListNode(cap % 10); cap = cap / 10; node = node.next; } if(cap != 0) { node.next = new ListNode(cap); } return newNode.next; } }
相关文章推荐
- (leetcode)2. 两个链表相加Add Two Numbers--Java
- LeetCode-2. Add Two Numbers(链表实现数字相加)
- 2.Add Two Numbers(medium)[链表处理 大数相加]
- Add Two Numbers 链表相加
- leetcode 5. 两个链表逐个元素相加 Add Two Numbers
- LeetCode OJ:Add Two Numbers (相加链表之数)
- Add Two Numbers Leetcode 链表相加
- LeetCode | Add Two Numbers(两个链表相加)
- Add Two Numbers 两个链表相加 python
- 两个链表的数字相加(简单题) add two numbers
- [Leetcode]Add Two Numbers链表数相加
- LeetCode-Add Two Numbers-链表数字相加-链表操作+加法进位
- 2. Add Two Numbers 给定的两个链表是逆序排列的,相加后放在一个新的链表里边
- 大整数相加--链表结构正向存储--Add Two Numbers II
- LeetCode2——Add Two Numbers(两个链表中的数字相加,形成新链表)
- [Leetcode #2]Add Two Numbers 链表存储的两个正数相加
- [Leetcode]Add Two Numbers 链表实现大数字相加
- [Leetcode #2]Add Two Numbers 链表存储的两个正数相加
- 链表:链表两数相加( LeetCode 2. Add Two Numbers(两数相加))
- LeetCode: 2_Add Two Numbers | 两个链表中的元素相加 | Medium