两个链表相加
2017-04-04 19:50
232 查看
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
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
package 训练; import java.util.*; public class 两个链表相加1 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); while(sc.hasNext()){ String[] a=sc.nextLine().split(" "); String[] b=sc.nextLine().split(" "); ListNode ahead=createListNode(a); ListNode bhead=createListNode(b); ListNode chead=addTwoNumbers(ahead,bhead); ListNode res=chead; while(res!=null){ System.out.print(res.val+" "); res=res.next; } System.out.println(); } } public static ListNode addTwoNumbers(ListNode l1, ListNode l2) { int sum=l1.val+l2.val; int j=sum/10; ListNode head=new ListNode(sum%10); ListNode node=head; l1=l1.next; l2=l2.next; while(l1!=null&&l2!=null){ sum=l1.val+l2.val+j; j=sum/10; node.next=new ListNode(sum%10); node=node.next; l1=l1.next; l2=l2.next; } while(l1!=null){ sum=l1.val+j; j=sum/10; node.next=new ListNode(sum%10); node=node.next; l1=l1.next; } while(l2!=null){ sum=l2.val+j; j=sum/10; node.next=new ListNode(sum%10); node=node.next; l2=l2.next; } if(j>0) node.next=new ListNode(j); return head; } static ListNode createListNode(String[] a){ ListNode head=new ListNode(Integer.parseInt(a[0])); ListNode node=head; for(int i=1;i<a.length;i++){ node.next=new ListNode(Integer.parseInt(a[i])); node=node.next; } return head; } }
相关文章推荐
- (链表实现)写出两个一元多项式相加的算法
- 线性表的应用——求解两个多项式相加问题描述(链表求解)
- 链表实现两个大正整数相加
- 两个链表的数字相加(简单题) add two numbers
- (链表实现)写出两个一元多项式相加的算法
- C++ 生成由两个链表相加生成的链表
- 两个链表相加
- LeetCode Add Two Numbers两个链表数值相加
- 两个一元多项式相加(链表 || 顺序表实现)
- 两个链表相加
- c++-add two numbers 两个链表相加
- 使用链表实现两个多项式相加和相乘
- (leetcode)2. 两个链表相加Add Two Numbers--Java
- LeetCode | Add Two Numbers(两个链表相加)
- 两个链表相加的和445. Add Two Numbers II
- [Leetcode #2]Add Two Numbers 链表存储的两个正数相加
- LinkLists 两个链表相加 @CareerCup
- 两个单链表生成相加链表
- 链表问题——两个单链表生成相加链表
- leetcode 5. 两个链表逐个元素相加 Add Two Numbers