其他分享
首页 > 其他分享> > 2018 spr cs61b dis3

2018 spr cs61b dis3

作者:互联网

链接 https://sp18.datastructur.es/materials/discussion/disc03.pdf

1.1

    public void insert(int item, int position){
        if(first == null || position = 0){
            addFirst(item);
            return;
        }
        IntNode p = first;
        for(int i = 0; i < position - 1 ;i++){
            p = p.next;
        }
        IntNode n = new IntNode(item, p.next);
        p.next = n;
    }

1.2

    public void reverse(){
        IntNode p,q,tmp;
        p = first;
        tmp = null
        while(P != null){
            q = p;
            p = p.next;
            q.next = tmp;
            tmp = q;
        }
    }

1.3

    public void reverseRec(){
        return RechHelp(first);
    }
    public void RecHelp(IntNode p){
        if(p == null or p.next == null){
            return p;
        }
        IntNode newnode = RecHelp(p.next);
        p.next.next = p;
        p.next = null;
        return newnode;
    }

2.1

    public static int[] insert(int[] arr, int item, int position){
        int[] ans = new int[arr.size()+1];
        int begin = 0;
        while(begin != position){
            ans[begin] = arr[begin];
            begin++;
        }
        ans[position] = item;
        begin++;
        while(begin != arr.size() + 1){
            ans[begin] = arr[begin-1];
        }
        return ans;
    }

2.2

    public static void reverse(int[] arr){
        for (int i = 0; i < arr.length / 2; i++) {
            int j = arr.length - i - 1;
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }

2.3

    public static int[] replicate(int[] arr) {
        int sum= 0;
        for (int item : arr) {
            sum+= item;
        }
        int[] result = new int[sum];
        int i = 0;
        for (int item : arr) {
        for (int counter = 0; counter < item; counter++) {
            result[i] = item;
            i++;
            }
        }
        return result;
    }

标签:arr,dis3,int,spr,cs61b,begin,next,item,public
来源: https://www.cnblogs.com/echoT/p/16272039.html