The sum of two linked lists

The Nat class represents Number (n), having a preliminary field that points to the number n-1, if pre is null, that means the number is zero.

public class Nat { 

     private final Nat pre; 
     public Nat (Nat pre) { this.pre = pre; } 
     public Nat () { this(null); } 
     public boolean isZero () { return pre == null; } 
     public Nat succ () { return new Nat(this); } 

    }

and I have to add a method that adds two numbers, I don’t understand how it should return Nat, which represents the sum of "this" and others!

public Nat plus (Nat other) { 

 if (other.isZero()) 
 return this; 

 return succ().plus(other.pre); 
} 

I think he creates "Nats" that point to the second Nat of this (pre) all the time .. Can someone help me?

+4
source share
4 answers

Well, if thisrepresents nand otherrepresents m, to calculate n+ is mequivalent to computing n+1+ m-1, which is what is succ().plus(other.pre)returned.

n+m, 0. this, other.isZero() .

+4

:

  • [null] → 0
  • [null → Nat1 (pre = null)] → 1
  • [null → Nat1 (pre = null) → Nat2 (pre = Nat1)] → 2
  • ..

plus():

, x+y (x-1)+(y+1) .. 0 + (y + x). , Nat, . , , other 0 - , , x .

:

[null -> Nat1(pre=null) -> Nat2(pre=Nat1) -> Nat3(pre=Nat2) -> Nat4(pre=Nat3) -> Nat5(pre=Nat5)]

, 3 2. other=Nat2 Nat3, Nat3's, Nat4, plus() other's , Nat1, , plus() Nat4's (Nat5) Nat1's , null, this, Nat5.

+1

n + k = (n + 1) + (k - 1)

k . Nats , Nat, Nat addend : Nat. , .

: 1 + 2

1.plus(2)
-- 1.succ().plus(1)
---- 1.succ().succ().plus(0)
------> 1.succ().succ() == 3 

EDIT: , , , , . plus() . .

+1

.

, plus (a+b a+1+b-1).

, , :

 public Nat (Nat pre) { this.pre = pre; } 
 ...
 public Nat succ () { return new Nat(this); } 

succ(), , this :

 public Nat succ () { return new Nat(this); } 

pre :

 public Nat (Nat pre) { this.pre = pre; } 

succ , - this.pre.pre....pre.

To understand better, you can introduce this (eventually add a few print lines to your methods):

public static void main(String[] args) {
    System.out.println("==== A new number is 0 ====");
    Nat n1 = new Nat();                 // 0 
    System.out.println(n1.isZero());    // true
    Nat n2 = new Nat();                 // 0
    System.out.println(n2.isZero());    // true
    Nat sum = n1.plus(n2);              // 0
    System.out.println(sum.isZero());   // true
    System.out.println(n2.isZero());    // true
    System.out.println("==== Test succ and pre ====");
    Nat one = n1.succ();                // 1
    System.out.println(one.isZero());   // false
    Nat two = one.plus(one);            // 1 + 1
    System.out.println(two.isZero());   // false
    System.out.println(two.pre.isZero());       // false
    System.out.println(two.pre.pre.isZero());   // true
}
0
source

All Articles