0

入力として整数とリンクを取り、位置入力整数のリンクの前にLinkedListにリンクを挿入するメソッドを実装したい、私が達成したこと:

public void insertBefore(int num, String data)
{
    Link current = head;
    int count = 0;
    while (current.next != null)
    {
        if(count == num) {
        Link n = new Link(data);
        n.next = current;
        current.next = n.previous;
        }
    }   
    current = current.next;
    count++;

    }

ただし、メソッドを呼び出すと何も起こらず、リンクが挿入されないため、メソッドの問題を知っている人はいますか?

4

1 に答える 1

1

前述のように、反復構造は反復メカニズムの外にあります。また、current の previous の next 要素を新しいリンクを指すように設定するのを忘れています。どのような種類のリンク リストを使用しているかはわかりませんが、改善点があります。

if (count == num) {
    Link n = new Link(data);
    n.next = current;
    current.previous.next = n;
    n.previous = current.previous;
    current.previous = n;
}

以下のコメントに応えて、コードに基づくより完全な改善:

public void insertBefore(int num, String data)
{
    Link current =  head;
    for (int count = 0; count < num && current.next != null; ++count)
    {
        current = current.next;
    }
    Link n = new Link(data);
    n.next = current;
    if (current.previous != null)
        current.previous.next = n;
    n.previous = current.previous;
    current.previous = n;
}
于 2012-07-18T23:11:48.193 に答える