list的正向和反向构造

0 阅读1分钟

` ``` public class IntList { public int first; public IntList rest;

public IntList(int a, IntList b) {
    first = a;
    rest = b;
}
public static int size(IntList p)
{
    int s=0;
    while(p!=null)
    {
        s=s+1;
        p=p.rest;
    }
    return s;
}
//return the ith item og the list
public  int get(int i)
{
    if(i==0)
    return first;
    return rest.get(i-1);

}

public static void main(String[] args) {
    // 正向建链
    IntList a = new IntList(5, null);
    a.rest = new IntList(10, null);
    a.rest.rest = new IntList(15, null);
    System.out.println(a.rest.rest.first);   // 应该打印 15

    // 反向建链:a 不换盒子,只换内容
    a = new IntList(15, null);
    a = new IntList(10, a);
    a = new IntList(5, a);
    System.out.println(a.first);             // 5
    System.out.println(a.rest.first);        // 10
    System.out.println(a.rest.rest.first);
    System.out.println(size(a));

    System.out.println(a.get(2));


}

}