2015-02-18 4 views
1

Я давно застрял в этой проблеме. Когда я запускаю его против моего теста на перемещение индекса 1, я получаю от [A][B][C][D][E] до [B][B][C][D][E]. Любая помощь приветствуется.Java: перемещение элемента из индекса в начало связанного списка?

public void moveToTop(int index) throws IllegalArgumentException { 
    if (index > size) { 
     throw new IllegalArgumentException(); 
    } 
    if (index == 0) { 
     return; 
    } else { 
     Node ref = first; 
     for (int i = 1; i < index; i++) { 
      ref = ref.next; 
     } 
     Node temp = null; 
     temp = ref.next; 
     ref = temp.next; 
     temp = first; 
     first = temp; 
    } 
} 

ответ

-1

Попробуйте использовать этот цикл вместо:

for (int i = 0; i <= index; i++) { 
     ref = ref.next; 
} 
0

Во-первых, установите индекс в цикле 0. С чем у вас там, его содержание не будет выполняться.

Во-вторых, внимательно посмотрите на следующую логику назначения. Вам нужно назначить узел ref переменной temp, ref для первого узла, а затем temp в ref.

1
void moveToTop(int index) { 
    // index should go until size - 1, not size 
    if (index >= size) throw new IllegalArgumentException(); 
    // index == 0 should return the list unmodified 
    if (index == 0) return; 

    // We start in the head 
    // first = A -> B -> C -> D -> E 
    // ref = A -> B -> C -> D -> E 
    Node ref = first; 
    for (int i = 0; i < index - 1; i++) { 
     // And loop until we find the node before the one we want to move 
     // For index = 1, we won't loop, so ref is still equal to first 
     ref = ref.next; 
    } 
    // temp = A.next => temp = B 
    Node temp = ref.next; 
    // ref (A) is the node before the one we wish to move 
    // A.next = B.next => A.next = C => ref = A -> C -> D -> E 
    ref.next = temp.next; 
    // B.next = A => temp = B -> A -> C -> D -> E 
    temp.next = first; 
    // first = B -> A -> C -> D -> E 
    first = temp; 
} 
Смежные вопросы