2016-10-23 5 views
0

그래서 저는 Java에서 링크드리스트를 처음 접했습니다. 연결된 목록에 항목을 추가하는 방법을 완료해야합니다. 아무도 내가 if 문을 완료하는 데 도움이 될 수 있도록 메서드가 올바르게 작동합니까? 도와 주셔서 감사합니다.이 방법을 사용하여 Java의 연결된 목록에 값을 추가하는 방법은 무엇입니까?

void insert(int item) 
    { 
//find location to insert 
Node current = head; 
Node prev = null; 
boolean located = false; 

while(!located && current != null)//correct location found 
{ 
    //I need to add a condition to the if statement below. What is the condition 
    if(item 
    current = current.link;//assign the next node from head to current node 
    } 

    //create new node and 
    //refer to the correct location in list 
    Node newNode = new Node(item, current); 

    //set link to refer to new node 
    if (current == head) 
    { 
    head = newNode;//new node to head 
    } 
    else 
    { 
    //place new node after previous LINK reference not the node itself 
    prev.link = newNode; 
    }  
} 
+0

나는 "당신"의 도움을 의미했습니다. – Jacob

+0

그런 다음 편집 할 수 있습니다. –

답변

0

목록이 정렬되어 있다고 가정합니다. 할 수없는 그 간단한 일이 목록의 시작에 새 항목을 추가하는 경우 :

head = new Node(item, head); 

경우에는, 그러나, 당신이보다 큰 첫 번째 항목을 찾을 필요가 다음 정렬 할 필요가있다 삽입하려는 항목 :

while (!located && current != null) { 
    if (item < current.item) { 
     prev = current; 
     current = current.link; 
    } else { 
     located = true; 
    } 
} 

Node newNode = new Node(item, current); 
if (current == head) { 
    head = newNode; 
} else { 
    prev.link = newNode; 
}  

이 코드는 새 항목을 삽입해야하는 시점을 찾고 있습니다. 이 시점에서 prevcurrent은 새 노드 앞뒤에있는 노드를 참조합니다. 목록의 끝에 도달하면 current은 null입니다.

관련 문제