2016-10-10 3 views
0

У меня возникли небольшие трудности с концепцией Recursive.Удаление коэффициентов из LinkedList рекурсивно с использованием индекса

Учитывая LinkedList с целочисленными значениями

L1 = (2->1->4->6->3) 
L2= (1->9->6->3) 

Функция должны удалить нечетное число из LinkedList, начиная с целым числом N и возвращает ссылку на новую голову

т.е.

L1.deleteOdd(2) = > (2->4->6) 

L2.deleteOdd(1) = > (6) 

Я реализовал нормальную итеративную функцию, которая выполняет эту работу, вот она

public node deleteOdd(int n) { 

    node head = this.head; 
    if (head == null) 
     return head; 
    while (head != null) { 
     if (head.data == n) { 
      node head2 = head; 
      while (head2.next != null) { 
       if (head2.next.data % 2 != 0) { 
        head2.next = head2.next.next; 
       } else { 
        head2 = head2.next; 
       } 
      } 
      if (head.data % 2 != 0) { 
       return head.next; 
      } 
      return head; 
     } 
     head = head.next; 

    } 
    return head; 
} 

Теперь я пытаюсь сделать рекурсивную функцию, я пытался что-то сделать, но похоже, что я чего-то не хватает.

Моя рекурсивная функция

public node DeleteOddR(int n) { 
    node head = this.head; 

    if (head == null) 
     return head; 
    if (head != null) { 
     if (head.data == n) { 
      node head2 = head; 
      if (head2.next.data % 2 != 0) 

      { 
       head2.next = head2.next.next; 

      } else { 

       head2 = head2.next; 
      } 

      if (head.data % 2 != 0) { 
       return DeleteOddR(head.next.data); 
      } else { 
       head.next = DeleteOddR(head.next.data); 
       return head; 
      } 

     } else { 
      head = head.next; 
     } 

    } 
    return head; 
} 

Результаты является

node f = l1.DeleteOddR(2); 
    display(f); // Gives- >2->3->4->6 

Я был бы признателен помогает ..

+0

Это не лучший пример для изучения рекурсивной концепции. Зачем использовать индекс со связанным списком? – passion

+0

Просто знайте, с чего начать. Это не «индекс», это число, где мы ищем его в связанном списке, и как только мы его нашли, мы используем узел, который содержит номер в качестве главы. Забыть обо всех элементах до этого l = (1,2,3,4,5,6,7,8,9,10,11,12) l.removeOdd (6) -> 6-> 8-> 10-> 12 (мой новый список) – Zok

ответ

1

я пишу один может удовлетворить ваши требования.
Сохраните предыдущий узел и повторите его использование.

public class LinkedList{ 

    public static void main(String[] args) { 
    LinkedList node0 = new LinkedList(0); 
    LinkedList node1 = new LinkedList(1); 
    LinkedList node2 = new LinkedList(2); 
    LinkedList node3 = new LinkedList(3); 
    LinkedList node4 = new LinkedList(4); 
    LinkedList node5 = new LinkedList(5); 
    LinkedList node6 = new LinkedList(6); 
    LinkedList node7 = new LinkedList(7); 
    LinkedList node8 = new LinkedList(8); 
    node0.setNext(node1); 
    node1.setNext(node2); 
    node2.setNext(node3); 
    node3.setNext(node4); 
    node4.setNext(node5); 
    node5.setNext(node6); 
    node6.setNext(node7); 
    node7.setNext(node8); 

    node0.removeOddFromVale(3, false); 
    System.out.println(); 
    } 

    public void removeOddFromVale(int value,boolean start){ 
    LinkedList head = this; 
    LinkedList prev = this; 

    if(!start){ 
     while(head != null){ 
     if(head.value == value){ 
      start = true; 
      break; 
     } 
     prev = head; 
     head = head.next; 
     } 
    } 

    if(prev != null && head != null){ 
     if(prev == head){ 
     head = head.next; 
     } 

     if (head != null) { 
     if (head.value % 2 == 0) { 
      prev.next = head.next; 
     } else { 
      prev = prev.next; 
      head = head.next; 
     } 
     if (prev != null) { 
      prev.removeOddFromVale(value, true); 
     } 
     } 
    } 

    } 

    private LinkedList next; 
    private int value; 

    public LinkedList(int value){ 
    this.value = value; 
    } 

    public LinkedList getNext() { 
     return next; 
    } 
    public void setNext(LinkedList next) { 
     this.next = next; 
    } 
    public int getValue() { 
     return value; 
    } 
    public void setValue(int value) { 
     this.value = value; 
    } 
} 
+0

Извините за мой поздний ответ, я очень ценю вашу работу, но со мной все плохо, я не знаю, почему, я тоже пробовал модифицировать его – Zok

+0

@Zok Я пробовал, это работает . Каков ваш тест? – passion

Смежные вопросы