2016-08-06 2 views
0

현재 AddAtIndex 메서드를 구현 중이며 대부분 잘 작동하는 것 같습니다. 그러나 제 방법은 JUnit 테스트를 통과하지 못하고 이유를 이해할 수 없습니다. 따라서, 나는 지금까지 수행 한 코드를 보여주기 위해 선택한 :현재 LinkedList에 AddAtIndex 메서드를 구현하고 있습니다.

** 
    * Add an element to the list at the specified index 
    * @param The index where the element should be added 
    * @param element The element to add 
    */ 
    public void add(int index, E element) //Method should be O(1) time. 
    { 
     // TODO: Implement this method 
     if (index < 0) { 
      System.out.println("Can't add an element at a negative index."); 
     } 
     int i = 0; 
     LLNode<E> currentNode = head.next; 
     while (i < size) { 
      if (i == index) { 
       LLNode<E> newNode = new LLNode<E>(element); 
       LLNode<E> tempNode = new LLNode<E>(currentNode.data); 

       currentNode.next = tempNode; 
       currentNode.data = newNode.data; 

       newNode.prev = currentNode.prev; 
       newNode.next = tempNode; 
       tempNode.prev = newNode; 
       size++; 
      } 
      currentNode = currentNode.next; 
      i++; 
     } 

    } 

코드 뒤에 내 생각 프로세스는 방법은 다음 링크 된리스트의 지정된 인덱스에있는 데이터를 대체, 새로운 노드를 생성하는 것입니다 . 그러나, 대체중인 노드의 데이터는 새 노드 다음의 다음 노드로 증가되는 임시 노드에 저장됩니다. 코드가 다소 엉성하기는하지만 필자는 구현에 대해 80 % 확신합니다. 구현을 시연 할 드라이버를 만들었습니다. 다음 드라이버 코드 :

public class LinkedListDriver { 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     MyLinkedList<String> nameList = new MyLinkedList<String>(); 
     nameList.add("Hamadi"); 
     nameList.add("Ballo"); 
     nameList.add(1, "Salisu"); 
     nameList.add(2, "Galo"); 
     System.out.println(nameList.toString()); 
     System.out.println(nameList.size()); 
     nameList.set(2, "Abdullahi"); 
     System.out.println(nameList.toString()); 
     nameList.remove(1); 
     System.out.println(nameList.toString()); 
     MyLinkedList<Integer> list1 = new MyLinkedList<Integer>(); 
     list1.add(65); 
     list1.add(21); 
     list1.add(42); 
     System.out.println(list1.toString()); 
     list1.remove(0); 
     System.out.println(list1.toString()); 
    } 

} 

다음과 같이 운전자의 출력은 : 그것은 AssertEquals 방법에 실패

:

List: Hamadi, Salisu, Galo, Ballo, 
4 
Replacing Galo with Abdullahi 
List: Hamadi, Salisu, Abdullahi, Ballo, 
Removing Salisu from the list 
List: Hamadi, Abdullahi, Ballo, 
List: 65, 21, 42, 
Removing 65 from the list 
List: 21, 42, 

유닛 테스트가 다음 오류 그러나 실패 :

shortList.add(2, "E"); 
     shortList.add(3, "F"); 
     **assertEquals("AddAtIndex: at position 2 ", "E", shortList.get(2)); //fails here** 
     assertEquals("AddAtIndex: at position 3 ", "F", shortList.get(3)); 
     assertEquals("AddAtIndex: List size is ", 6, shortList.size()); 

내가 뭘 잘못하고 있는지 알고 싶습니다. 나는 이것을 문자 그대로 완전히 알아 냈다. 비록 나의 AddAtindex 메소드에 대해 조금 벗어난 것이있다. 감사!

+2

디버거를 사용하고 포인터가 어떻게 움직이는 지 확인하십시오. –

+0

초기 출력에서 ​​추가 메소드가 대부분 작동한다고 말할 수 있습니다. –

+0

당신은'for' -loops에 대해서도 배워야합니다 : for (int i = 0; i

답변

2

tempNode은 필요하지 않습니다. newNode을 만들고 currentNode과 이전 노드 사이에 올바르게 삽입하십시오.

또한 목록의 시작 (이전) 또는 끝 (다음 없음)에 요소를 추가 할 가능성을 고려해야합니다.

+0

거기서 당신은 나쁜 값을 돌려 주려고 어떻게해야하는지 모르겠습니다. 머리 부분으로 알려진 빈 센티넬 노드입니다. 나는 더 구체적이어야 했어, 고마워! – Linuxn00b

0

머리와 꼬리를 센티넬 노드로 사용했습니다. 목록에 추가 할 새 노드를 만들었습니다.

public boolean add(E element) { 
     // create new element 
     LLNode<E> variable = new LLNode(element); 
     variable.next = null; 
     variable.prev = null; 

     // if element is null, throw exception 
     if (element == null) { 
      // return false; 
      throw new NullPointerException("Element is null"); 
     } else { 
      // get the value stored in tail.prev in variable temp. 
      variable.prev = tail.prev; 
      variable.next = tail; 
      // now modify the tail node prev and new node next 
      tail.prev = variable; 

      // get prev node next link changed 
      variable.prev.next = variable; 

      // update size 
      if (head.next.next != tail) { 
       size++; 
      } 
      return true; 
     } 
    } 
관련 문제