2016-06-28 3 views
0

링크 된 목록 2를 링크 된 목록 1의 끝에 병합해야하는 코드에서 누락 된 부분을 찾아 내려고했습니다. 바로 지금 두 번째 목록의 마지막 요소를 가져 오는 중입니다. 그걸 돌려 줬어.Java를 사용하여 두 개의 연결된 목록을 병합

내가 사용하려고했던 논리는 첫 번째 목록 (L1)을 걷고 그 요소를 하나씩 new_list에 추가 한 다음 두 번째 목록 (L2)에 대해 동일하게 처리하는 것입니다. L1. 나는 또한 L1 또는 L2를 수정하는 것을 피하려고 노력하고 있는데, 이것이 내가 왜 new_list를 만들었는지에 대한 것이다.

도움을 주시면 감사하겠습니다.

public NodeList(int item, NodeList next) { 
    this.item = item; 
    this.next = next; 
} 

public static NodeList merge(NodeList l1, NodeList l2) { 

    NodeList new_list = new NodeList(l1.item, l1.next); 
    NodeList new_list2 = new NodeList(l2.item, l2.next); 

    while (true) { 
     if (new_list.next == null) { 
      if (new_list2.next == null) { 
       return new_list; 
      } 
      else { 
       new_list.next = new NodeList(new_list2.next.item, new_list2.next.next); 
       new_list2 = new_list2.next; 
      } 

     } 
     else { 
      new_list.next = new NodeList(new_list.next.item, new_list.next.next); 
      new_list = new_list.next; 
     } 
    } 
} 
+0

귀하의 while 루프는 결코 종료되지 않습니다 –

+2

그것은 'Node'와'NodeList' 개념을 함께 섞어 놓은 것 같습니다. –

+0

@SeanPatrickFloyd 두 목록이 모두 null이면 코드는 호출하는 메서드로 돌아갑니다. – azurefrog

답변

2

목록의 첫 번째 노드에 대한 참조를 유지해야합니다. 아래 예제에서, 나는 또한 논리적으로 당신이하려고하는 것이기 때문에 미리 결정된 종료 조건을 가지고 루프를 두개로 나눕니다. 기존 목록의 요소에 대한 참조는 수정하지 않으려한다고 언급 했으므로 결코 복사하지 않습니다. 나는 그러나 입력 로컬 참조 증가 않는 : 당신이 볼 수 있듯이

public static NodeList merge(NodeList l1, NodeList l2) { 

    NodeList new_head = new NodeList(0, null); 
    NodeList new_node = new_head; 

    for(; l1 != null; l1 = l1.next) { 
     new_node.next = new NodeList(l1.item, null); 
     new_node = new_node.next; 
    } 

    for(; l2 != null; l2 = l2.next) { 
     new_node.next = new NodeList(l2.item, null); 
     new_node = new_node.next; 
    } 
    return new_head.next; 
} 

, 이것은 코드의 반복을 많이 가지고가, 그래서 쉽게리스트의 임의의 번호를 일반화 할 수 있습니다

public static NodeList merge(NodeList... l) { 

    NodeList new_head = new NodeList(0, null); 
    NodeList new_node = new_head; 

    for(NodeList ln in l) { 
     for(; ln != null; ln = ln.next) { 
      new_node.next = new NodeList(ln.item, null); 
      new_node = new_node.next; 
     } 
    } 
    return new_head.next; 
} 
+0

아, 고마워요! 내가하려고했던 것보다 훨씬 더 분명해. –

관련 문제