链表4:链表的加法 算法 第1张

解题思路:

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

1.创建一个结点类

2.创建一个加法方法,一个输出方法

3.加法方法和输出方法均使用递归的方式

此题一共需要三个链表:两个用来存储两组数值,一个用存储它们两个相加的结果(注意进位)

 

对9237与8624,这两组数进行试验

代码如下:

 1 //结点类 
 2 class Node{
 3     int data;
 4     Node next;
 5 
 6     public Node() {}
 7     public Node(int data) {
 8         this.data=data;
 9     }
10 }
11 
12 public class PlusLinkNode {
13 
14     public static void main(String[] args) {
15         Node node1=new Node(7);
16         node1.next=new Node(3);
17         node1.next.next=new Node(2);
18         node1.next.next.next=new Node(9);
19         
20         Node node2=new Node(4);
21         node2.next=new Node(2);
22         node2.next.next=new Node(6);
23         node2.next.next.next=new Node(8);
24         
25         Node node3=plus(node1,node2);
26         print(node3);
27     }
28     
29     public static Node plus(Node a,Node b) {return plus2(a,b,0);}
30     public static Node plus2(Node a,Node b,int i) {
31         //i为进位数
32         if(a==null&&b==null&&i<1)
33             return null;
34         int value=i;
35         if(a!=null)
36             value+=a.data;
37         if(b!=null)
38             value+=b.data;
39         Node result=new Node(value%10);
40         result.next=plus2(a==null?null:a.next,b==null?null:b.next,value>=10?1:0);
41         return result;
42     }
43     
44     //打印方法
45     public static void print(Node node) {
46         if(node==null)
47             return ;
48         print(node.next);
49         System.out.print(node.data);
50     }
51 
52 }

 

结果:

链表4:链表的加法 算法 第2张

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄