您的位置:首页 > 其它

链表求和I

2017-06-22 21:17 239 查看
你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中
相反
的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。您在真实的面试中是否遇到过这个题? Yes样例给出两个链表 
3->1->5->null
 和 
5->9->2->null
,返回 
8->0->8->null
import 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;}}}
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode