カスタムリンクリストを作成しようとしていますが、これまでのところ、一般的な構造と2つの最も簡単な方法(insertFirstとdeleteFirst)を作成する方法を理解しました。次に実行したいのは、リンクのインデックスを取得し、その場所の文字列を返すgetメソッドを作成することです。各リンクにインデックスまたはアドレスが割り当てられていないため、リンクリスト内の特定の場所を参照する方法がわかりません。first.nextと書くと、2番目の項目が取得され、first.next.nextと3番目の項目が取得されることがわかります。ただし、インデックスパラメーター(getメソッドに渡されるパラメーター)の作成方法を理解する必要があります。 )私のリスト内の適切な場所と相関させます....どうすればこれを行うことができますか?
ずさんなコードは許してください...リンクリストの構造を把握したら、必ず詳細をクリーンアップします。
これが私のコードです、ありがとうございます!
テストコード
class LinkedListTest {
public static void main(String[] args)
{
LinkedList list = new LinkedList();
list.insertFirst("cat");
list.insertFirst("dog");
list.insertFirst("fish");
list.insertFirst("cow");
list.insertFirst("horse");
list.insertFirst("pig");
list.insertFirst("chicken");
System.out.println(list.get(1));
}
}
私のクラス
public class LinkedList
{
private Link first;
public LinkedList()
{
first = null;
}
public void insertFirst(String word)
{
Link link = new Link(word);
link.next = first;
first = link;
}
public String deleteFirst()
{
Link temp = first;
first = first.next;
return temp.toString();
}
public String get(int index)
{
// the following is just to show that I can access different links
// by adding more .next's after first--- but i need a way to access
// the correct link based on the index passed in
// String second = first.next.item;
String third = first.next.next.item;
// String fourth= first.next.next.next.item
return third;
}
}
public class Link
{
public String item;
public Link next;
//Link constructor
public Link(String theItem)
{
item = theItem;
}
}