链表求和I
2017-06-22 21:17
239 查看
你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中
相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。您在真实的面试中是否遇到过这个题? Yes样例给出两个链表
3->1->5->null和
5->9->2->null,返回
8->0->8->nullimport java.util.Scanner;/*** 你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。样例给出两个链表 3->1->5->null 和 5->9->2->null,返回 8->0->8->null* @author Dell**/public class Test167 {public static ListNode addLists(ListNode l1, ListNode l2){if(l1==null)return l2;if(l2==null)return l1;ListNode result=new ListNode(-1);ListNode p=l1;ListNode q=l2;ListNode r=result;int c=0;while(p!=null&&q!=null){int he=p.val+q.val;if(c==1){he++;c=0;}if(he>=10){he=he-10;c=1;}ListNode temp=new ListNode(he);r.next=temp;r=r.next;p=p.next;q=q.next;}while(p!=null){if(c==1){p.val++;c=0;}if(p.val>=10){p.val=p.val-10;c=1;}r.next=p;r=r.next;p=p.next;}while(q!=null){if(c==1){q.val++;c=0;}if(q.val>=10){q.val=q.val-10;c=1;}r.next=q;r=r.next;q=q.next;}if(c==1){ListNode temp=new ListNode(1);r.next=temp;}return result.next;}public static void main(String[] args) {Scanner sc=new Scanner(System.in);int n1=sc.nextInt();int n2=sc.nextInt();ListNode list1=new ListNode(-1);ListNode p=list1;for(int i=0;i<n1;i++){ListNode temp=new ListNode(sc.nextInt());p.next=temp;p=p.next;}ListNode list2=new ListNode(-1);ListNode q=list2;for(int i=0;i<n2;i++){ListNode temp=new ListNode(sc.nextInt());q.next=temp;q=q.next;}ListNode result=addLists(list1.next,list2.next);while(result!=null){System.out.print(result.val);result=result.next;}}}
相关文章推荐
- 链表求和-LintCode
- 链表求和
- 链表求和
- LintCode【简单】167. 链表求和 。代码及思路
- 链表求和
- leetcode——Add Two Numbers 两个链表表示的正整数对其求和(AC)
- 单链表应用--一元多项式求和
- Leetcode第二题,用链表实现两个非负整数求和
- 链表求和问题
- java两链表求和
- Linkcode 167 链表求和
- 数据结构实践——链表:多项式求和
- LintCode-链表求和
- 程序员面试经典--双链表求和
- python_lintcode_167链表求和
- 链表实现多项式求和求积
- 链表之多项式求和
- 链表求和(LintCode)
- 链表多项式求和
- LintCode167:链表求和