刷题--两个链表生成相加链表

两个链表,分别表示2个整数,每个链表的节点含有数值0-9

比如9->3->7 和 6->3 相加,得到1->0->0->0

解:将2个链表分别反向,将反向后的链表相加,将得到的链表反向,即可得到解

 1 // 两个单链表生成相加链表
 2     public static Node addList(Node head1, Node head2){
 3         if(head1 == null)
 4             return head2;
 5         if(head2 == null)
 6             return head1;
 7         if(head1==null && head2==null)
 8             return null;
 9 
10         Node rehead1 = reverseList1(head1);
11         Node rehead2 = reverseList1(head2);
12         Node sumhead = new Node((rehead1.val + rehead2.val) % 10);
13 
14         Node cur1 = rehead1.next;
15         Node cur2 = rehead2.next;
16         Node cur3 = sumhead;
17         int carry = (rehead1.val + rehead2.val) / 10;
18         while(cur1!=null && cur2!=null){
19             cur3.next = new Node((cur1.val + cur2.val + carry)%10);
20             carry =(cur1.val + cur2.val)/10;
21             cur3 = cur3.next;
22             cur1 = cur1.next;
23             cur2 = cur2.next;
24         }
25         while(cur1!=null){
26             cur3.next = new Node((cur1.val + carry) % 10);
27             carry = (cur1.val + carry) / 10;
28             cur3 = cur3.next;
29             cur1 = cur1.next;
30         }
31         while(cur2!=null){
32             cur3.next = new Node((cur2.val+carry) % 10);
33             carry = (cur2.val+carry) / 10;
34             cur3 = cur3.next;
35             cur2 = cur2.next;
36         }
37         if(carry != 0){
38             cur3.next = new Node(carry);
39         }
40         head1 = reverseList1(rehead1);
41         head2 = reverseList1(rehead2);
42         return reverseList1(sumhead);
43     }
44 
45     // 链表反向
46     public static Node reverseList1(Node head){
47         if(head==null || head.next==null)
48             return head;
49         Node cur = head;
50         Node pre = null;
51         Node next = null;
52         while (cur!=null && cur.next!=null){
53             next = cur.next;
54             cur.next = pre;
55             pre = cur;
56             cur = next;
57         }
58         cur.next = pre;
59         return  cur;
60     }
View Code

 

转载于:https://www.cnblogs.com/HITSZ/p/7764344.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值