单链表实现

//IntList and Linked Data Structures

//IntList
/* Defines a recursive list of integers.*/

public class IntList{
    public int head;
    public IntList tail;

    public IntList(int h, IntList t){
        head = h;
        tail = t;
    }

/* Returns the size of the recursive IntList */

    public int size(){
        if(this.tail == null)
            return 1;
        int personInFrontOfMeSize = this.tail.size();
        return personInFrontOfMeSize + 1;
    }

/* Iterative methods are often uglier. */

    public int iterativeSize(){
        IntList p = this;
        int size = 0;
        while(p != null){
            size = size + 1;
            p = p.tail;
        }
        return size;
    }

/index /

    public int get(int i){
        if(i == 0){
            return this.head;
        }
        return this.tail.get(i - 1);
    }

    public static void main(String[] args){
        IntList L = new IntList(10, null);
        L.tail = new IntList(15, null);
        System.out.println(L.head);
        System.out.println(L.tail.head);
        System.out.println(L.size());
        System.out.println(L.iterativeSize());
    }
 }

//IntListOps

public class IntListOps{
    /* returns identical to L, but with every item
      *incremented by x, L cannot change. 
     */
public static IntList incrList(IntList L, int x){
    if(L == null)
        return null;
    int newHead = L.head + x;
    IntList newTail = incrList(L.tail, x);
    return new IntList(newHead, newTail);
}
public static void main(String[] args){
    //测试代码
}

此段代码为CS61b课程第三节课的演示代码,由于没有直接现成的可复制粘贴,便手打于此,以便今后翻阅。主要部分便是递归与迭代方面的运用,也是着重记录这部分。对于CS61b的课程,先是介绍java的基础知识,之后便是数据结构的介绍。目前只看了前三节课,之后的课程还需继续坚持,同时,作业和lab也要尽量写。

这个暑假已经被自己荒废了不少,继续努力吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值