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

两个链表,分别表示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

 

posted @ 2017-10-31 23:03  Apollo_zhanghongbo  阅读(1349)  评论(0编辑  收藏  举报