两个链表相加的和445. Add Two Numbers II
来源:互联网 发布:3d大型网络手机游戏 编辑:程序博客网 时间:2024/06/08 09:23
题目:
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first 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
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */class Solution { /* 解题思路:将链表存入集合中,然后相加即可,定义一个变量flage记录进位 */ public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode result=new ListNode(0);//头结点 LinkedList<Integer> list1=new LinkedList<Integer>(); LinkedList<Integer> list2=new LinkedList<Integer>(); while(l1!=null){ list1.add(l1.val); l1=l1.next; }//while while(l2!=null){ list2.add(l2.val); l2=l2.next; }//while int flage=0; //头插法建立链表,集合是先进后出的方式 while(list1.size()!=0&&list2.size()!=0){ int num=list1.removeLast()+list2.removeLast()+flage; flage=num/10; num=num%10; ListNode temp=new ListNode(num); temp.next=result.next; result.next=temp; }//while while(list1.size()!=0){ int num=list1.removeLast()+flage; flage=num/10; num=num%10; ListNode temp=new ListNode(num); temp.next=result.next; result.next=temp; } while(list2.size()!=0){ int num=list2.removeLast()+flage; flage=num/10; num=num%10; ListNode temp=new ListNode(num); temp.next=result.next; result.next=temp; } //考虑进位的时候,两个集合均为空的情况,例如{5} {5}相加之后需要进位1 if(flage!=0){ ListNode temp=new ListNode(flage); temp.next=result.next; result.next=temp; } return result.next; }}
阅读全文
0 0
- 两个链表相加的和445. Add Two Numbers II
- 445. Add Two Numbers II | 链表的整数相加
- leeecode 445. Add Two Numbers II 链表相加
- 445. Add Two Numbers II 两个数字相加 2
- leetcode_445. Add Two Numbers II 单链表表示的两个大数相加
- LeetCode Add Two Numbers两个链表数值相加
- LeetCode | Add Two Numbers(两个链表相加)
- (leetcode)2. 两个链表相加Add Two Numbers--Java
- Add Two Numbers 两个链表相加 python
- 两个链表的数字相加(简单题) add two numbers
- Add Two Numbers 把两个以链表形式表示的数相加 @LeetCode
- [Leetcode #2]Add Two Numbers 链表存储的两个正数相加
- Add Two Numbers创建list和两个list相加
- Add Two Numbers 链表相加
- Add Two Numbers 链表相加
- Add Two Numbers Leetcode 链表相加
- Leetcode Add two numbers链表相加
- 【LeetCode】链表相加 Add Two Numbers
- 基于windows10和VS2015环境下配置zbar-code开发环境
- 【摄影技巧】摄影的骨架——构图(只为方便查找)
- android 高级之旅 (十三) 真! 如何判断去电是否接通? 已解决!
- 用notepad++连接远程服务器
- Javascript进阶
- 两个链表相加的和445. Add Two Numbers II
- LeetCode(11)——Container With Most Water
- Oracle 过程 Exception
- [Axure]关于微信实现横纵向拖动效果的一些想法
- ACM-ICPC国际大学生程序设计竞赛北京赛区(2017)网络赛 题目1 : Visiting Peking University
- 游戏里的人生-扎克斯
- STL源码解析(2) -- 迭代器iterator与traits
- leetcode--Remove Elements
- PAT乙级 1055. 集体照 (25)