0

ArrayLists で動作するコードを、単独でリンクされたリストで動作するコードに変換しようとしています。配列リストは、以前に作成された Shape オブジェクトで構成されており、動作はわかっています。次に、新しい形状を配列リストの最後に追加できます。また、インデックス参照を使用して、このリストから特定の形状を削除することもできます。ただし、これをリンクされたリストに切り替えると、必要なものがまったく得られません。配列リストのコードは次のとおりです。

import java.util.ArrayList;

public class ShapeLinkedList {
    ArrayList<Shape> list = new ArrayList<Shape>();

    public ShapeLinkedList() {
    }

    public void addToRear(Shape shape) {
        list.add(shape);
        System.out.println("Added "+shape);
    }

    public Shape get(int index) {
        return list.get(index);
    }

    public int size() {
        return list.size();
    }

    public Shape remove(int index) {
        Shape temp = list.remove(index);
        System.out.println("Removed "+temp);
        return temp;
    }
}

メソッドの名前を変更することはできず、同じメソッドをすべて使用する必要があります。したがって、これはリンクされたリストについてこれまでのところ私が持っているものです:

public class ShapeLinkedList {
    ShapeNode head;
    int count = 0;

    public ShapeLinkedList() {}

    public void addToRear(Shape shape) {
        ShapeNode end = new ShapeNode(shape);
        if (head == null) {
            head = end;
        }
        //loop through Linked List until we find the end of the list
        while (head.next != null) {
            head = head.next;
            count++;
        }
        //set the new node to the Shape shape and the next one will be null
        head.next = end;
        count++;
        //System.out.println("Added " + shape);
    }

    public Shape get(int index) {
        for (int i = 0; i <= index; i++) {

        }
        Shape rem = ;
        return rem
    }

    public int size() {
        return count;
    }

    public Shape remove(int index) {
        if (index == 0) {
            Shape temp = head;
            head = head.next;
        } else if () {
            Shape temp = ;
        }
        //System.out.println("Removed " + temp);
        return temp;
    }

    private class ShapeNode {
        Shape shp;
        ShapeNode next;

        public ShapeNode(Shape shp) {
            this.shp = shp;
            next = null;
        }
    }
}

LinkedList のインデックスを見つける方法がわからず、そのインデックスで特定の形状タイプを参照する方法がわからないため、Shape のゲッターを構築するのに助けが必要です。また、remove メソッドについても助けが必要です。問題を抱えている最初のゲッターに必要な情報を取得したら、2番目の問題を解決できるはずです。誰にも役立つ提案はありますか?

4

1 に答える 1

0
 public Shape get(int index) {
        ShapeNode temp = head;
        while(index-- > 0) {
            temp = temp.next;
        }
        if(temp == null)
            throw new IndexOutOfBoundsException("Invalid index : " + index);
        Shape rem = temp.shp;
        return rem;
    }

しかし、これはO(n)linkedListです。

于 2012-12-04T13:52:15.043 に答える