CS61BHomework3作业回顾(附代码)

Part 1.

smoosh()函数,目的是将数组中出现的所有数字产生重复的部分删除,例如11223334444经过smoosh函数后会变成1234.

    public static void smoosh(int[] ints) {
        // Fill in your solution here.  (Ours is twelve lines long, not counting
        // blank lines or lines already present in this file.)

        int current = 0;
        for (int i = current + 1; i < ints.length; i++){
            if (ints[current] != ints[i]){
                current++;
                ints[current] = ints[i];
            }
        }

        for (int i = current + 1; i < ints.length; i++){
            ints[i] = -1;
        }


    }

Part 2.

squish()函数,与smoosh功能相同,只不过要用链表来实现。size>2的检测是题目给的。

    public void squish() {
        // Fill in your solution here.  (Ours is eleven lines long.)
        SListNode currentNode = head;

        while (size > 2 && currentNode.next != null){
            if (currentNode.item.equals(currentNode.next.item)){
                currentNode.next = currentNode.next.next;
            } else {
                currentNode = currentNode.next;
            }
        }
    }

Part 3.

twin()函数,目的是将数字出现的频率x2.同样用链表实现。SListNode有两个constructor,刚好其中一个可以在新建node的时候直接赋予item和next,思路与part2相似。

    public void twin() {
        // Fill in your solution here.  (Ours is seven lines long.)

        SListNode current = head;
        while (current != null){
            current.next = new SListNode(current.item,current.next);
            current = current.next.next;
        }

    }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值