• 链表4:链表的加法


    解题思路:

    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 }

    结果:

  • 相关阅读:
    delphi XE8 for android ----一个无意闯入的世界
    不能Ping和telnet的
    syslog-ng内容讲解
    《信息安全系统设计与实现》学习笔记7
    缓冲区溢出实验
    2.3.1测试
    鲲鹏服务器测试
    cat userlist
    需求分析
    《信息安全系统设计与实现》学习笔记5
  • 原文地址:https://www.cnblogs.com/LgxBoKeYuan/p/10203200.html
Copyright © 2020-2023  润新知