2014-04-06 9 views
0

내 목록 끝에 요소를 추가하는 데 문제가 있습니다. 목록의 시작 부분에 계속 추가됩니다. 나는 잠시 동안 이것에 있었고, 단지 붙어서 길을 잃었다. 여기 노드 끝에 새 요소 추가 (Java)

public class RefUnsortedList<T> implements ListInterface<T> { 

     protected int numElements;  // number of elements in this list 
     protected LLNode<T> currentPos; // current position for iteration 

     // set by find method 
     protected boolean found;  // true if element found, else false 
     protected LLNode<T> location; // node containing element, if found 
     protected LLNode<T> previous; // node preceeding location 

     protected LLNode<T> list;  // first node on the list 

     public RefUnsortedList() { 
     numElements = 0; 
     list = null; 
     currentPos = null; 
     } 

     public void add(T element) { 
     // Adds element to this list. 


     LLNode<T> newNode = new LLNode<T>(element); 

     newNode.setLink(list); 
     list = newNode; 
     numElements++; 

내 주요 클래스 :

RefUnsortedList<Patient> patient1 = new RefUnsortedList<Patient>(); 
Patient entry; 
entry = new Patient("Tam Ngo", "0848896"); 
patient1.add(entry); 
entry = new Patient("Mike You", "0848896"); 
patient1.add(entry); 

System.out.println(patient1.toString()); 
+0

당신이 조금하고있는 일을 반성하십시오. 새로운 노드를 만들고, 새로운 노드의 링크를 이전 목록으로 설정하고 "목록의 첫 번째 노드"를 새로운 노드. 그러면 노드가 목록에 첫 번째로 놓입니다. –

답변

0

작성한대로 list 변수는 목록의 첫 번째 노드를 보유합니다.

list = newNode; 

이 줄은 즉시 목록의 시작 부분에 추가 할 노드를 설정합니다 : 지금, 당신의 add 방법은 라인을 포함!

가능한 수정 사항은 두 개의 포인터를 유지하는 것입니다. 하나는 목록의 시작 부분 (검색을 위해)이고 다른 하나는 마지막 요소입니다.이를 last이라고합니다. 여기

last.setLink(newNode); 
last = newNode; 

, 우리는 새로운 노드로 현재 마지막 노드에서 링크를 설정 한 다음 새 노드에게 새로운 마지막 노드를 만들 :이 경우, 다음을 수행 할 수있는 노드를 추가 할 수 있습니다.

희망이 도움이됩니다.

+0

내가 무슨 말하는지 알 것 같아. 수업에서 머리글과 예고편을 배웠지 만 RefUnsortedList에 구현하는 방법을 모르겠습니다. 내 이해가 막연하다. – tamngoman